Files1
12:09:39Department of Computer Science-BGU
Open File
FILE fopen(const char filename , const char mode)
: כאשר filename :
הינו מצביע למחרוזת תווים שהינה שם הקובץ אותו רוצים לפתוח ) יש לציין מסלול מלא ביחס למיקום התוכנית( .
mode :
הינו מצביע למחרוזת תווים אשר מציינת את מטרת פתיחת הקובץ . האופציות הן :
"r.פתיחת קובץ טקסט לקריאה - ""w.פתיחת קובץ טקסט לכתיבה - ""a .פתיחת קובץ טקסט להוספה, בסופו של הקובץ - "
2
12:09:39Department of Computer Science-BGU
Open File (cont.)
במידה והפונקציהfopen)( ,הצליחה בפתיחת הקובץ יוחזר מצביע לקובץ . NULLאחרת יוחזר
: מספר נקודות1.במידה ונפתח לכתיבה או הוספה, קובץ שלא קיים, יווצר קובץ בשם זה)2 במידה ונפתח לכתיבה קובץ שקיים, הכתיבה לקובץ זה תמחק את הקיים)(overwrite).3 במידה ונפתח לקריאה קובץ שלא קיים או ללא הרשאה מתאימה, הפונקציה תחזיר)
NULL.
כפי שניתן לראות הפונקציהfopen)( מחזירה מצביע לקובץ שאיתו אנו רוצים . FILEלעבוד. בכדי לשמור כתובת זו נגדיר משתנה מטיפוס
אם הפונקציה תחזיר למשתנה זהNULL סימן שהפתיחה לא הצליחה ולכן אין טעם להמשיך במהלך ביצוע התוכנית.
3
12:09:40Department of Computer Science-BGU
Example
" לקריאה :in.datלדוגמא, פתיחת הקובץ "
FILE fin ; fin=fopen(in.dat , r); if( fin==NULL) {
printf(Error in opening file %s\n, in.dat) ;exit(1) ;
}הסבר :
כמצביע לקובץ.fin הצהרנו על ,( ראשית1
" , כלומר r עם שם הקובץ אותו אנו רוצים לפתוח באופן פתיחה ")(fopen( קריאה ל - 2לקריאה.
בדקנו אם הקריאה נכשלה, אם כן מודפסת הודעה )(fopen( לאחר הקריאה לפונקציה 3
1 . כאשר נהוג להחזיר )(exit מתאימה ומתבצעת קריאה לפונקציה
כמציין סיום לא נורמלי של התוכנית.
4
12:09:40Department of Computer Science-BGU
סגירת קובץ
בסיום השימוש בקובץ או עם סיום התוכנית חייבים לסגור אתהקבצים שפתחנו. אם לא נעשה זאת, חלק מהמידע שכתבנו
לקובץ עלול להיאבד. לצורך כך קיימת פונקצית הספרייה fclose)( - אשר אב הטיפוס שלה מוגדר גם כן ב stdio.h
והוא :
int fclose( FILE )
5
12:09:41Department of Computer Science-BGU
Character in file
Get a character int fgetc( FILE *stream ); Each of these functions returns the character read.
To indicate a read error or end-of-file condition, fgetc and getchar return EOF.
Put a character int fputc( int c, FILE *stream );
6
12:09:41Department of Computer Science-BGU
Example
Write program that uses fgetc and fputc to read words from the input file and place them into the output file with one space a separator.
The maximal word size is 80 characters.
7
12:09:41Department of Computer Science-BGU
Solution
#include <stdio.h>#include <string.h>#include <stdlib.h>#define MAX 80void main (){
FILE *source, *result;char string [MAX+1];int ch, i=0;
if((source=fopen("source.txt","r"))==NULL{
printf("Can't open the file\n");exit(1);
}if((result= fopen("result.txt","w"))==NULL){
printf("Can't open the file\n");exit(1);
}
while((ch = fgetc(source))!=EOF)if( ch!=' ') string[i++]=ch;else if(i) {
string[i]='\0';for(i=0; string[i]; i++)
fputc(string[i],result);fputc(' ',result);i=0;
}if(i) {
string[i]='\0';for(i=0; string[i]; i++) fputc(string[i], result);
}fclose(source);fclose(result);
}
8
12:09:41Department of Computer Science-BGU
String in file
Get a string
char *fgets( char *string, int n, FILE *stream );
Put a string
int fputs( char *string, FILE *stream );
9
12:09:41Department of Computer Science-BGU
Properties of fgets
The fgets function reads characters from the current stream position to and including the first newline character, to the end of stream, or until the number of characters read is equal to n-1 , whichever comes first. The result stored in string is appended with a NULL character. The newline character, if read, is included in the string.
12:09:41Department of Computer Science-BGU
10
Example
Write program that uses fgets to read lines from the input file. Then the program uses fputs to put words into the output file retaining one space between the words.
The maximal line size is 80 characters.
11
12:09:41Department of Computer Science-BGU
Solution
#include <stdio.h>#include <string.h>#define MAX 80 void main(){
FILE *source, *result;char string [MAX+1];char *save;int i=0, mode=1;
if((source=
fopen("source.txt","r"))==NULL){ printf("Can't open the file\
n"); exit(1);
}if((result=
fopen("result.txt","w"))==NULL) {printf("Can't open the file\
n");exit(1);
}
while(fgets(string,MAX+1,source)) { save=string; while(*(save)){
if(mode) { if(*(save)==' ') mode=0; save++;}else if(*(save)!=' ') {
mode=1; save++; } else
strcpy(save,save+1);fputs(string,result);
} fclose(source);fclose(result);}
12
12:09:41Department of Computer Science-BGU
Formatted Input/Output
int fscanf( FILE *stream, const char *format [, argument ]... );
int fprintf( FILE *stream, const char
*format [, argument ]...);
13
12:09:41Department of Computer Science-BGU
Example
Write program that uses fscanf and fprintf to read words from the input file and places them into the output file with one space a separator.
The maximal word size is 80 characters.
14
12:09:41Department of Computer Science-BGU
Solution#include <stdio.h>#include <stdlib.h>#define MAX 80 void main(){
FILE *source, *result;char string [MAX+1];if(((source=fopen("source.txt","r"))==NULL) || ((result=fopen("result.txt","w"))==NULL)) {
printf("Can't open the file\n");exit(1);
}while((fscanf(source,"%s", string))!=EOF)
fprintf(result,"%s ",string); fclose(source); fclose(result);}
15
12:09:42Department of Computer Science-BGU
fscanf - format specification Fields
A format specification has the following form:%[*] [width] type
If the first character in the set is a caret (^), the effect is reversed: The input field is read up to the first character that does appear in the rest of the character set.
For example: fscanf( ptr, "%20[^#]%9d%*c", name, &id);
the function fscanf reads 20 characters, or till letter (‘#') , or till newline from the input stream and stores them in field name, then it reads the next 9 characters and converts them into integer id, then it reads one symbol which is not stored.
16
12:09:42Department of Computer Science-BGU
Example 1
של הסמסטר , עבור כל נתוני המבחנים ים כילכל הקבצים שבשאלה מ הבאים:פרטים שמכילה את השורה אחתסטודנט
תווים(20שם הסטודנט )עד ( .9מספר ת.ז)תווים ( 4קוד הקורס )ספרות ספרות(3ן בקורס )ציו ( 4קוד הקורס )ספרות ספרות(.....)לפי מספר הקורסים שהסטודנט נבחן בהם(3ן בקורס )ציו
ובכל שורה הקורסים הקבצים מסודרים לפי מספר ת.ז. בסדר עולה
ממוינים בסדר עולה.
12:09:42Department of Computer Science-BGU
17
Example 1
כתוב פונקציהfinal כארגומנטים שלושה מצביעים לקבצים: שמקבלתמצביע לקובץ קיים של ציוני מועד א', מצביע לקובץ קיים של ציוני מועד
.ב', ומצביע לקובץ חדש של הציונים סופיים הציונים הסופיים בכל הקורסים הפונקציה מעתיקה לקובץ החדש את
שהסטודנטים נבחנו לפי הכללים הידועים לכם שסטודנט יכול להבחן בקורס מסוים במועד אחד בלבד)א' או ב'( או בשני מועדים במקרה הזה
הציון הסופי בקורס הוא הציון של מועד ב'. אין לקרוא קובץ יותר מפעם אחת. הגבלה : דינמי וכו'(אין להעתיק קובץ למבנה נתונים אחר )מערך
12:09:42Department of Computer Science-BGU
18
Example 1
void final(FILE* f1, FILE* f2, FILE* f3){int flag1, flag2, flag11, flag22,course1,course2,grade1,grade2;char name1[21],name2[21],id1[10],id2[10],string1[200],string2[200];char *s1,*s2;flag1=fscanf(f1,"%[^0-9]%9s%s*c",name1,id1,string1);s1=string1;
flag2=fscanf(f2,"%[^0-9]%9s%s*c",name2,id2,string2);s2=string2;while (flag1 != EOF || flag2 != EOF){
if(flag2==EOF || flag1!=EOF && strcmp(id1, id2)<0){fprintf(f3,"%s%s%s\n",name1,id1,string1);
flag1=fscanf(f1,"%[^0-9]%9s%s*c",name1,id1,string1);
s1=string1;} else
12:09:42Department of Computer Science-BGU
19
Example 1
if(flag1==EOF || flag2!=EOF && strcmp(id1, id2)>0){ fprintf(f3,"%s%s%s\n",name2,id2,string2); flag2=fscanf(f2,"%[^0-9]%9s%s%*c",name2,id2,string2);
s2=string2; }else{ fprintf(f3,"%s%s",name2,id2);flag11=sscanf(string1,"%4d%3d",&course1,&grade1);
flag22=sscanf(string2,"%4d%3d",&course2,&grade2); while (flag11 == 2 || flag22 == 2){ if(flag22<2 || flag11==2 && course1<course2){
fprintf(f3,"%4d%3d",course1,grade1); s1 +=7;flag11=sscanf(s1,"%4d%3d",&course1,&grade1); }else
if(flag11<2 || flag22==2 && course1>course2){ fprintf(f3,"%4d%3d",course2,grade2); s2 +=7; flag22=sscanf(s2,"%4d%3d",&course2,&grade2); }else{ fprintf(f3,"%4d%3d",course2,grade2); s1 += 7; flag11=sscanf(s1,"%4d%3d",&course1,&grade1);
s2 += 7; flag22=sscanf(s2,"%4d%3d",&course2,&grade2);} } fprintf(f3,"\n");
flag1=fscanf(f1,"%[^0-9]%9s%s*c",name1,id1,string1);s1=string1;flag2=fscanf(f2,"%[^0-9]%9s%s*c",name2,id2,string2);s2=string2; } } /// end of while}void main(){ FILE *f1, *f2, *f3; f1=fopen("first.dat","r");f2=fopen("second.dat","r"); f3=fopen("final.dat","w"); if(!f1 || !f2 || !f3){printf("Can't open file!\n"); exit(1); } final(f1,f2,f3); fclose(f1); fclose(f2); fclose(f3);}
12:09:43Department of Computer Science-BGU
20
Example 1
12:09:43Department of Computer Science-BGU
21
12:09:43Department of Computer Science-BGU
22