Files

22
Files 1 21:45:44 Department of Computer Science-BGU

description

Files. Open File. FILE  fopen (const char  filename , const char  mode) כאשר : filename : הינו מצביע למחרוזת תווים שהינה שם הקובץ אותו רוצים לפתוח ( יש לציין מסלול מלא ביחס למיקום התוכנית) . mode : הינו מצביע למחרוזת תווים אשר מציינת את מטרת פתיחת הקובץ . האופציות הן : - PowerPoint PPT Presentation

Transcript of Files

Page 1: Files

Files1

20:22:03Department of Computer Science-BGU

Page 2: Files

Open File

FILE fopen(const char filename , const char mode)

: כאשר filename :

הינו מצביע למחרוזת תווים שהינה שם הקובץ אותו רוצים לפתוח ) יש לציין מסלול מלא ביחס למיקום התוכנית( .

 mode :

הינו מצביע למחרוזת תווים אשר מציינת את מטרת פתיחת הקובץ . האופציות הן :

 "r.פתיחת קובץ טקסט לקריאה - ""w.פתיחת קובץ טקסט לכתיבה - ""a .פתיחת קובץ טקסט להוספה, בסופו של הקובץ - "

2

20:22:03Department of Computer Science-BGU

Page 3: Files

Open File (cont.)

במידה והפונקציהfopen)( ,הצליחה בפתיחת הקובץ יוחזר מצביע לקובץ . NULLאחרת יוחזר

: מספר נקודות1.במידה ונפתח לכתיבה או הוספה, קובץ שלא קיים, יווצר קובץ בשם זה)2 במידה ונפתח לכתיבה קובץ שקיים, הכתיבה לקובץ זה תמחק את הקיים)(overwrite).3 במידה ונפתח לקריאה קובץ שלא קיים או ללא הרשאה מתאימה, הפונקציה תחזיר)

NULL.

כפי שניתן לראות הפונקציהfopen)( מחזירה מצביע לקובץ שאיתו אנו רוצים . FILEלעבוד. בכדי לשמור כתובת זו נגדיר משתנה מטיפוס

אם הפונקציה תחזיר למשתנה זהNULL סימן שהפתיחה לא הצליחה ולכן אין טעם להמשיך במהלך ביצוע התוכנית.

 

3

20:22:03Department of Computer Science-BGU

Page 4: Files

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

20:22:04Department of Computer Science-BGU

Page 5: Files

סגירת קובץ

בסיום השימוש בקובץ או עם סיום התוכנית חייבים לסגור אתהקבצים שפתחנו. אם לא נעשה זאת, חלק מהמידע שכתבנו

לקובץ עלול להיאבד. לצורך כך קיימת פונקצית הספרייה fclose)( - אשר אב הטיפוס שלה מוגדר גם כן ב stdio.h

והוא :

 

int fclose( FILE )

5

20:22:04Department of Computer Science-BGU

Page 6: Files

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

20:22:04Department of Computer Science-BGU

Page 7: Files

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

20:22:05Department of Computer Science-BGU

Page 8: Files

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

20:22:05Department of Computer Science-BGU

Page 9: Files

String in file

Get a string

char *fgets( char *string, int n, FILE *stream );

Put a string

int fputs( char *string, FILE *stream );

9

20:22:05Department of Computer Science-BGU

Page 10: Files

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.

20:22:05Department of Computer Science-BGU

10

Page 11: Files

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

20:22:05Department of Computer Science-BGU

Page 12: Files

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

20:22:05Department of Computer Science-BGU

Page 13: Files

Formatted Input/Output

int fscanf( FILE *stream, const char *format [, argument ]... );

 int fprintf( FILE *stream, const char

*format [, argument ]...);

13

20:22:05Department of Computer Science-BGU

Page 14: Files

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

20:22:05Department of Computer Science-BGU

Page 15: Files

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

20:22:06Department of Computer Science-BGU

Page 16: Files

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

20:22:06Department of Computer Science-BGU

Page 17: Files

Example 1

של הסמסטר , עבור כל נתוני המבחנים ים כילכל הקבצים שבשאלה מ הבאים:פרטים שמכילה את השורה אחתסטודנט

תווים(20שם הסטודנט )עד ( .9מספר ת.ז)תווים ( 4קוד הקורס )ספרות ספרות(3ן בקורס )ציו ( 4קוד הקורס )ספרות ספרות(.....)לפי מספר הקורסים שהסטודנט נבחן בהם(3ן בקורס )ציו

  ובכל שורה הקורסים הקבצים מסודרים לפי מספר ת.ז. בסדר עולה

ממוינים בסדר עולה.

20:22:06Department of Computer Science-BGU

17

Page 18: Files

Example 1

כתוב פונקציהfinal כארגומנטים שלושה מצביעים לקבצים: שמקבלתמצביע לקובץ קיים של ציוני מועד א', מצביע לקובץ קיים של ציוני מועד

.ב', ומצביע לקובץ חדש של הציונים סופיים הציונים הסופיים בכל הקורסים הפונקציה מעתיקה לקובץ החדש את

שהסטודנטים נבחנו לפי הכללים הידועים לכם שסטודנט יכול להבחן בקורס מסוים במועד אחד בלבד)א' או ב'( או בשני מועדים במקרה הזה

הציון הסופי בקורס הוא הציון של מועד ב'. אין לקרוא קובץ יותר מפעם אחת. הגבלה : דינמי וכו'(אין להעתיק קובץ למבנה נתונים אחר )מערך

20:22:06Department of Computer Science-BGU

18

Page 19: Files

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

20:22:06Department of Computer Science-BGU

19

Page 20: Files

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);}  

20:22:07Department of Computer Science-BGU

20

Page 21: Files

Example 1

20:22:07Department of Computer Science-BGU

21

Page 22: Files

20:22:07Department of Computer Science-BGU

22