/* ** $Id: files.c 776 2008-02-16 01:38:17Z phf $ ** ** Here's a mess of code we used in lecture to look at the ** basics of files in C. I simply added some comments, you ** can find better explanations in the K&R book as well as ** the stdio man page. */ #include #include #define SIZE 1024 int main(void) { puts( "File stuff... :-)" ); /* ** First an example that essentially is cat on ** a file, our own source code in this case. I ** had this as the only example in lecture in ** Spring 2008, that's why I had all those ** exit codes in there. Just commented out to ** also run the rest of this demo. :-) */ FILE *me = fopen("files.c", "r"); if (me != NULL) { puts("files: yeah, found and then opened myself for reading!"); // this is the "cat" like loop, now using // specific file pointers int c; while ((c = fgetc(me)) != EOF) { fputc(c, stdout); } int res = fclose(me); if (res == EOF) { puts("files: can't get rid of myself (well, my own source code)!"); // return EXIT_FAILURE; } // return EXIT_SUCCESS; } else { puts("files: can't find myself (well, my own source code)!"); // return EXIT_FAILURE; } /* ** Now we'll use fgets() to read "line by line" or ** some approximation thereof. */ /* A buffer we'll use for input and output. */ char buffer[SIZE]; /* You can open a file for reading this way. */ FILE *file = fopen( "files.c", "r" ); /* You need to check if the file could be opened. */ if (file != NULL) { puts( "Opened the file!" ); /* You can use ftell() to see where you are in a file. */ printf( "Pos: %ld", ftell( file ) ); /* Using fgets() you can read a line up to a maximum size. */ while (fgets( buffer, 1024, file ) != NULL) { printf( "%s", buffer ); printf( "Pos: %ld", ftell( file ) ); } /* When fgets() returns NULL we reached the end of the file. */ /* We still need to close the file though! */ fclose( file ); puts( "Closed the file!" ); } else { puts( "File not found!" ); } /* ** You can open a file for writing this way. If it already ** exists, it will be "truncated" and you'll "lose" whatever ** was in it before. (In lecture we did "a" for append as ** well.) */ file = fopen( "test-file", "w" ); if (file != NULL) { puts( "File created!" ); /* You can write stuff to the file of course. */ fputs( "Habeas Corpus sure was nice...", file ); /* Close it! */ fclose( file ); puts( "File closed!" ); } else { puts( "Can't create file!" ); } /* ** You can open a file for writing this way without losing ** data. Yes, confusing... */ file = fopen( "test-file", "r+" ); if (file != NULL) { puts( "File opened!" ); /* You can go to an arbitrary position in the file. */ fseek( file, 1024, SEEK_SET ); /* And you can write stuff to the file of course. */ fputs( "AT 1024!", file ); /* What thou fopenst thou shallst fclose! :-) */ fclose( file ); puts( "File closed!" ); } else { puts( "Can't create file!" ); } return EXIT_SUCCESS; }