Presentation is loading. Please wait.

Presentation is loading. Please wait.

Files in C Rohit Khokher. Files in C Real life situations involve large volume of data and in such cases, the console oriented I/O operations pose two.

Similar presentations


Presentation on theme: "Files in C Rohit Khokher. Files in C Real life situations involve large volume of data and in such cases, the console oriented I/O operations pose two."— Presentation transcript:

1 Files in C Rohit Khokher

2 Files in C Real life situations involve large volume of data and in such cases, the console oriented I/O operations pose two major problems It becomes cumbersome and time consuming to handle large volumes of data through terminals. The entire data is lost when either the program is terminated or computer is turned off therefore it is necessary to have more flexible approach where data can be stored on the disks and read whenever necessary, without destroying the data. This method employs the concept of files to store data.

3 File management in C A.File management in C, B.File operation functions in C, C.Defining and opening a file, D.Closing a file, E.The getw and putw functions, F.The fprintf & fscanf functions, G.Random access to files and fseek function.

4 File operation functions in C: Function NameOperation fopen() Creates a new file for use Opens a new existing file for use fcloseCloses a file which has been opened for use getc()Reads a character from a file putc()Writes a character to a file fprintf()Writes a set of data values to a file fscanf()Reads a set of data values from a file getw()Reads a integer from a file putw()Writes an integer to the file fseek()Sets the position to a desired point in the file ftell()Gives the current position in the file rewind()Sets the position to the begining of the file

5 Defining and opening a file FILE *fp; fp=fopen(“filename”,”mode”); The variable fp is a pointer to the data type FILE. The File is a structure that is defined in the I/O Library. “filename” the file named filename and assigns an identifier to the FILE type pointer fp. The mode defines the purpose R open the file for read only. W open the file for writing only. A open the file for appending data to it.

6 Defining and opening a file FILE *p1, *p2; p1=fopen(“data”,”r”); p2=fopen(“results”,”w”); In these statements the p1 and p2 are created and assigned to open the files data and results respectively the file data is opened for reading and result is opened for writing. In case the results file already exists, its contents are deleted and the files are opened as a new file. If data file does not exist error will occur.

7 Files in C In C, each file is simply a sequential stream of bytes. C imposes no structure on a file. A file must first be opened properly before it can be accessed for reading or writing. When a file is opened, a stream is associated with the file. Successfully opening a file returns a pointer to (i.e., the address of) a file structure, which contains a file descriptor and a file control block.

8 Files in C The statement: FILE *fptr1, *fptr2 ; declares that fptr1 and fptr2 are pointer variables of type FILE. They will be assigned the address of a file descriptor, that is, an area of memory that will be associated with an input or output stream. Whenever you are to read from or write to the file, you must first open the file and assign the address of its file descriptor (or structure) to the file pointer variable.

9 Opening Files The statement: fptr1 = fopen ( "mydata", "r" ) ; would open the file mydata for input (reading). The statement: fptr2 = fopen ("results", "w" ) ; would open the file results for output (writing). Once the files are open, they stay open until you close them or end the program (which will close all files.)

10 Testing for Successful Open If the file was not able to be opened, then the value returned by the fopen routine is NULL. For example, let's assume that the file mydata does not exist. Then: FILE *fptr1 ; fptr1 = fopen ( "mydata", "r") ; if (fptr1 == NULL) { printf ("File 'mydata' did not open.\n") ; }

11 Reading From Files In the following segment of C language code: int a, b ; FILE *fptr1, *fptr2 ; fptr1 = fopen ( "mydata", "r" ) ; fscanf ( fptr1, "%d%d", &a, &b) ; the fscanf function would read values from the file "pointed" to by fptr1 and assign those values to a and b.

12 End of File The end-of-file indicator informs the program when there are no more data (no more bytes) to be processed. There are a number of ways to test for the end-of- file condition. One is to use the feof function which returns a true or false condition: fscanf (fptr1, "%d", &var) ; if ( feof (fptr1) ) { printf ("End-of-file encountered.\n”); }

13 End of File There are a number of ways to test for the end-of-file condition. Another way is to use the value returned by the fscanf function: int istatus ; istatus = fscanf (fptr1, "%d", &var) ; if ( istatus == EOF ) { printf ("End-of-file encountered.\n”) ; }

14 Writing To Files Likewise in a similar way, in the following segment of C language code: int a = 5, b = 20 ; FILE *fptr2 ; fptr2 = fopen ( "results", "w" ) ; fprintf ( fptr2, "%d %d\n", a, b ) ; the fprintf functions would write the values stored in a and b to the file "pointed" to by fptr2.

15 Closing Files The statements: fclose ( fptr1 ) ; fclose ( fptr2 ) ; will close the files and release the file descriptor space and I/O buffer memory.

16 Reading and Writing Files #include int main ( ) { FILE *outfile, *infile ; int b = 5, f ; float a = 13.72, c = 6.68, e, g ; outfile = fopen ("testdata", "w") ; fprintf (outfile, "%6.2f%2d%5.2f", a, b, c) ; fclose (outfile) ;

17 Reading and Writing Files infile = fopen ("testdata", "r") ; fscanf (infile,"%f %d %f", &e, &f, &g) ; printf ("%6.2f%2d%5.2f\n", a, b, c) ; printf ("%6.2f,%2d,%5.2f\n", e, f, g) ; } **************************** , 5, 6.68

18 Closing a file The input output library supports the function to close a file; it is in the following format. fclose(file_pointer); A file must be closed as soon as all operations on it have been completed. This would close the file associated with the file pointer. Observe the following program. …. FILE *p1 *p2; p1=fopen (“Input”,”w”); p2=fopen (“Output”,”r”); …. fclose(p1); fclose(p2) ;

19 Reading & writing getc and putc functions The getc and putc functions are analogous to getchar and putchar functions and handle one character at a time. The putc function writes the character contained in character variable c to the file associated with the pointer fp1. Example putc(c,fp1); The getc function is used to read a character from a file that has been open in read mode. c=getc(fp2).

20 Example #include main() { file *f1; printf(“Data input output”); f1=fopen(“Input”,”w”); /*Open the file Input*/ while((c=getchar())!=EOF) /*get a character from key board*/ putc(c,f1); /*write a character to input*/ fclose(f1); /*close the file input*/ printf(“nData outputn”); f1=fopen(“INPUT”,”r”); /*Reopen the file input*/ while((c=getc(f1))!=EOF) printf(“%c”,c); fclose(f1); } End_of_File Check for feof and ferror functions

21 Reading & writing The getw and putw functions These are integer-oriented functions. They are similar to get c and putc functions and are used to read and write integer values. These functions would be usefull when we deal with only integer data. The general forms of getw and putw are: putw(integer,fp); getw(fp);

22 Reading & writing The getw and putw functions /*Example program for using getw and putw functions*/ #include main() { FILE *f1,*f2,*f3; int number I; printf(“Contents of the data filenn”); f1=fopen(“DATA”,”W”); for(I=1;I< 30;I++) { scanf(“%d”,&number); if(number==-1) break; putw(number,f1); } fclose(f1); f1=fopen(“DATA”,”r”); f2=fopen(“ODD”,”w”); f3=fopen(“EVEN”,”w”); while((number=getw(f1))!=EOF)/* Read from data file*/ { if(number%2==0) putw(number,f3);/*Write to even file*/ else putw(number,f2);/*write to odd file*/ } fclose(f1); fclose(f2); fclose(f3); f2=fopen(“ODD”,”r”); f3=fopen(“EVEN”,”r”); printf(“nnContents of the odd filenn”); while(number=getw(f2))!=EOF) printf(“%d%d”,number); printf(“nnContents of the even file”); while(number=getw(f3))!=EOF) printf(“%d”,number); fclose(f2); fclose(f3); }

23 fprintf & fscanf functions The fprintf and fscanf functions are identical to printf and scanf functions except that they work on files. The first argument of theses functions is a file pointer which specifies the file to be used. The general form of fprintf is fprintf(fp,”control string”, list); Where fp id a file pointer associated with a file that has been opened for writing. The control string is file output specifications list may include variable, constant and string. fprintf(f1,%s%d%f”,name,age,7.5); Here name is an array variable of type char and age is an int variable

24 fprintf & fscanf functions The general format of fscanf is fscanf(fp,”controlstring”,list); This statement would cause the reading of items in the control string. Example: fscanf(f2,”5s%d”,item,&quantity”); Like scanf, fscanf also returns the number of items that are successfully read.

25 /*Program to handle mixed data types*/ #include main() { FILE *fp; int num,qty,I; float price,value; char item[10],filename[10]; printf(“Input filename”); scanf(“%s”,filename); fp=fopen(filename,”w”); printf(“Input inventory datann”0; printf(“Item namem number price quantityn”); for I=1;I< =3;I++) { fscanf(stdin,”%s%d%f%d”,item,&number,&price,&quality); fprintf(fp,”%s%d%f%d”,itemnumber,price,quality); } fclose (fp); fprintf(stdout,”nn”); fp=fopen(filename,”r”); printf(“Item name number price quantity value”); for(I=1;I< =3;I++) { fscanf(fp,”%s%d%f%d”,item,&n umber,&prince,&quality); value=price*quantity”); fprintf(“stdout,”%s%d%f%d%dn ”,item,number,price,quantity,va lue); } fclose(fp); }

26 Random access to files Sometimes it is required to access only a particular part and not the complete file. This can be accomplished by using the following function: fseek function: The general format of fseek function is a s follows: fseek(file pointer,offset, position);

27 Random access to files This function is used to move the file position to a desired location within the file. Fileptr is a pointer to the file concerned. Offset is a number or variable of type long, and position in an integer number. Offset specifies the number of positions (bytes) to be moved from the location specified by the position. The position can take the 3 values. Value Meaning 0 Beginning of the file 1 Current position 2 End of the file.

28 The Preprocessor The #include Preprocessor Directive The #define Preprocessor Directive: Symbolic Constants The #define Preprocessor Directive: Macros Conditional Compilation The #error and #pragma Preprocessor Directives The # and ## Operators Line Numbers Predefined Symbolic Constants Assertions

29 Introduction Preprocessing – Occurs before program compiled Inclusion of external files Definition of symbolic constants Macros Conditional compilation Conditional execution – All directives begin with # Can only have whitespace before directives – Directives not C statements Do not end with ;

30 The #include Preprocessor Directive #include directive – Puts copy of file in place of directive Seen many times in example code – Two forms #include – For standard library header files – Searches predesignated directories #include "filename" – Searches in current directory – Normally used for programmer-defined files

31 The #include Preprocessor Directive Usage – Loading header files #include – Programs with multiple source files – Header file Has common declarations and definitions Classes, structures, enumerations, function prototypes Extract commonality of multiple program files

32 The #define Preprocessor Directive: Symbolic Constants #define – Symbolic constants Constants represented as symbols When program compiled, all occurrences replaced – Format #define identifier replacement-text #define PI – Everything to right of identifier replaces text #define PI= Replaces PI with "= " Probably an error – Cannot redefine symbolic constants

33 The #define Preprocessor Directive: Symbolic Constants Advantages – Takes no memory Disadvantages – Name not be seen by debugger (only replacement text) – Do not have specific data type const variables preferred

34 The #define Preprocessor Directive: Macros Macro – Operation specified in #define – Intended for legacy C programs – Macro without arguments Treated like a symbolic constant – Macro with arguments Arguments substituted for replacement text Macro expanded – Performs a text substitution No data type checking

35 The #define Preprocessor Directive: Macros Example #define CIRCLE_AREA( x ) ( PI * ( x ) * ( x ) ) area = CIRCLE_AREA( 4 ); becomes area = ( * ( 4 ) * ( 4 ) ); Use parentheses – Without them, #define CIRCLE_AREA( x ) PI * x * x area = CIRCLE_AREA( c + 2 ); becomes area = * c + 2 * c + 2; which evaluates incorrectly

36 The #define Preprocessor Directive: Macros Multiple arguments #define RECTANGLE_AREA( x, y ) ( ( x ) * ( y ) ) rectArea = RECTANGLE_AREA( a + 4, b + 7 ); becomes rectArea = ( ( a + 4 ) * ( b + 7 ) ); #undef – Undefines symbolic constant or macro – Can later be redefined

37 Conditional Compilation Control preprocessor directives and compilation – Cannot evaluate cast expressions, sizeof, enumeration constants Structure similar to if #if !defined( NULL ) #define NULL 0 #endif – Determines if symbolic constant NULL defined – If NULL defined, defined( NULL ) evaluates to 1 #define statement skipped – Otherwise #define statement used – Every #if ends with #endif

38 Conditional Compilation Can use else – #else – #elif is "else if" Abbreviations – #ifdef short for #if defined(name) – #ifndef short for #if !defined(name)

39 Conditional Compilation "Comment out" code – Cannot use /*... */ with C-style comments Cannot nest /* */ – Instead, use #if 0 code commented out #endif – To enable code, change 0 to 1

40 Conditional Compilation Debugging #define DEBUG 1 #ifdef DEBUG cerr << "Variable x = " << x << endl; #endif – Defining DEBUG enables code – After code corrected Remove #define statement Debugging statements are now ignored

41 The #error and #pragma Preprocessor Directives #error tokens – Prints implementation-dependent message – Tokens are groups of characters separated by spaces #error 1 - Out of range error has 6 tokens – Compilation may stop (depends on compiler) #pragma tokens – Actions depend on compiler – May use compiler-specific options – Unrecognized #pragma s are ignored

42 42 The # and ## Operators # operator – Replacement text token converted to string with quotes #define HELLO( x ) cout << "Hello, " #x << endl; – HELLO( JOHN ) becomes cout << "Hello, " "John" << endl; Same as cout << "Hello, John" << endl; ## operator – Concatenates two tokens #define TOKENCONCAT( x, y ) x ## y – TOKENCONCAT( O, K ) becomes OK

43 Line Numbers #line – Renumbers subsequent code lines, starting with integer #line 100 – File name can be included – #line 100 "file1.c" Next source code line is numbered 100 For error purposes, file name is "file1.c" Can make syntax errors more meaningful Line numbers do not appear in source file

44 Predefined Symbolic Constants Five predefined symbolic constants – Cannot be used in #define or #undef

45 Assertions assert is a macro – Header – Tests value of an expression If 0 ( false ) prints error message, calls abort – Terminates program, prints line number and file – Good for checking for illegal values If 1 ( true ), program continues as normal – assert( x <= 10 ); To remove assert statements – No need to delete them manually – #define NDEBUG All subsequent assert statements ignored

46 Preprocessing language The preprocessing language After tokenization, the stream of tokens may simply be passed straight to the compiler’s parser. However, if it contains any operations in the preprocessing language, it will be transformed first. This stage corresponds roughly to the standard’s “translation phase 4” and is what most people think of as the preprocessor’s job. The preprocessing language consists of directives to be executed and macros to be expanded.Its primary capabilities are: Inclusion of header files. These are files of declarations that can be substituted into your program. Macro expansion. You can define macros, which are abbreviations for arbitrary fragments of C code. The preprocessor will replace the macros with their definitions throughout the program. Some macros are automatically defined for you. Conditional compilation. You can include or exclude parts of the program according to various conditions. Line control. If you use a program to combine or rearrange source files into an intermediate file which is then compiled, you can use line control to inform the compiler where each source line originally came from. Diagnostics. You can detect problems at compile time and issue errors or warnings.

47 Header Files Include Syntax( #include or #include "file" Suppose the file myfile.h contains the statement char *test (void); and the program file program.c’ contains\ int x; #include “myfile.h" int main (void) { puts (test ()); } int x; char *test (void); Int main (void) {puts (test ()); }

48 Search Path for include files /usr/local/include libdir/gcc/target/version/include /usr/target/include /usr/include

49 Macros A macro is a fragment of code which has been given a name. An object-like macro is a simple identifier which will be replaced by a code fragment. Create macros with the ‘#define’ directive. #define BUFFER_SIZE 1024 foo = (char *) malloc (BUFFER_SIZE); foo = (char *) malloc (1024);

50 Macros #define NUMBERS 1, \ 2, \ 3 int x[] = { NUMBERS }; int x[] = { 1, 2, 3 }; It is equivalent to Macro can be declared using multiple lines

51 Macros fax= X; #define X 4 bar = X; produces fax = X; bar = 4; #define TABLESIZE BUFSIZE #define BUFSIZE 1024 TABLESIZE BUFSIZE 1024 TABLESIZE is expanded first to produce BUFSIZE, then that macro is expanded to produce the final result, 1024.

52 Macros #define BUFSIZE 1020 #define TABLESIZE BUFSIZE #undef BUFSIZE #define BUFSIZE 37 undefine Now TABLESIZE expands (in two stages) to 37.

53 Function-like Macros #define lang_init() c_init() lang_init() c_init() A function-like macro is only expanded if its name appears with a pair of parentheses after it. If you write just the name, it is left alone. This can be useful when you have a function and a macro of the same name, and you wish to use the function sometimes. extern void foo(void); #define foo() /* optimized inline version */... foo(); funcptr = foo; The function pointer will get the address of the real function. The call to foo() will use the macro

54 Function-like Macros #define lang_init () c_init() lang_init() () c_init()() There should not be blank If blank then lang_init() will expand to

55 Macro Arguments #define min(X, Y) ((X) < (Y) ? (X) : (Y)) x = min(a, b);  x = ((a) < (b) ? (a) : (b)); y = min(1, 2);  y = ((1) < (2) ? (1) : (2)); z = min(a + 28, *p);  z = ((a + 28) < (*p) ? (a + 28): (*p)); min (min (a, b), c) is first expanded to min (((a) < (b) ? (a) : (b)), (c)) and then to ((((a) < (b) ? (a) : (b))) < (c) ? (((a) < (b) ? (a) : (b))) : (c)) Example

56 Stringification (#) Convert a macro argument into a string constant. #define WARN_IF(EXP) \ do { if (EXP) \ fprintf (stderr, "Warning: " #EXP "\n"); } \ while (0) WARN_IF (x == 0);  do { if (x == 0) fprintf (stderr, "Warning: " "x == 0" "\n"); } while (0);

57 Stringification (#) #define xstr(s) str(s) #define str(s) #s #define foo 4 str (foo)  "foo" xstr (foo)  xstr (4)  str (4)  "4"

58 Concatenation ‘##’ This is called token pasting or token concatenation. The ‘##’ preprocessing operator performs token pasting. When a macro is expanded, the two tokens on either side of each ‘##’ operator are combined into a single token, which then replaces the ‘##’ and the two original tokens in the macro expansion. struct command { char *name; void (*function) (void); }; struct command commands[] = { { "quit", quit_command }, { "help", help_command },... }; #define COMMAND(NAME) { #NAME, NAME ## _command } struct command commands[] = { COMMAND (quit), COMMAND (help),... };

59 Predefined Macros __FILE__ __LINE__ This macro expands to the name of the current input file, in the form of a C string constant. This macro expands to the current input line number, in the form of a decimal integer constant. __DATE__This macro expands to a string constant that describes the date on which the preprocessor is being run. The string constant contains eleven characters and looks like "Feb ". __TIME__This macro expands to a string constant that describes the time at which the preprocessor is being run. The string constant contains eight characters and looks like "23:59:01".

60 Undefining and Redefining Macros #define FOO 4 x = FOO;  x = 4; #undef FOO x = FOO;  x = FOO;

61 Conditional Syntax #ifdef MACRO controlled text #endif /* MACRO */ #if expression controlled text #endif /* expression */ #if expression text-if-true #else /* Not expression */ text-if-false #endif /* Not expression */ #if defined MACRO is precisely equivalent to #ifdef MACRO. #if X == 1... #else /* X != 1 */ #if X == 2... #else /* X != 2 */... #endif /* X != 2 */ #endif /* X != 1 */ #if X == 1... #elif X == 2... #else /* X != 2 and X != 1*/... #endif /* X != 2 and X != 1*/ Elif

62 #Pragmas The ‘#pragma’ directive is the method specified by the C standard for providing additional information to the compiler. It is an implementation oriented directive. #pragma loop_opt(on) causes loop optimization in a program #error The ‘#error’ produces error messages during debugging. #if !defined(FILE_GRAPHICS) #error NO GRAPHICS FACILITY #endif.


Download ppt "Files in C Rohit Khokher. Files in C Real life situations involve large volume of data and in such cases, the console oriented I/O operations pose two."

Similar presentations


Ads by Google