C - File I/O
A file represents a sequence of bytes, regardless of it being a text file or a binary file.
Opening Files
You can use the fopen()
function to create a new file or to open an existing file.
File *fopen(const char *filename, const char *mode);
No | Mode & Description |
---|---|
1 | r Opens an existing text file for reading purpose. |
2 | w Opens a text file for writing. If it does not exist, then a new file is created. Here your program will start writing content from the beginning of the file. |
3 | a Opens a text file for writing in appending mode. If it does not exist, then a new file is created. Here your program will start appending content in the existing file content. |
4 | r+ Opens a text file for both reading and writing. |
5 | w+ Opens a text file for both reading and writing. It first truncates the file to zero length if it exists, otherwise creates a file if it does not exist. |
6 | a+ Opens a text file for both reading and writing. It creates the file if it does not exist. The reading will start from the beginning but writing can only be appended. |
If you are going to handle binary files, then you will use following access modes instead of the above mentioned ones −
"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"
Writing a File
int fputc( int c, FILE *fp ); //char
//return c, then written on success, otherwise EOF.
int fputs( const char *s, FILE *fp ); //string
//return nonnegative value on success, otherwise EOF.
int fprintf(fp, const char *format); //string
Closing a File
To close a file, use the fclose( )
function.
int fclose( FILE *fp );
Example Writing
#include <stdio.h>
main() {
FILE *fp; //flie
fp = fopen("/c/test.txt", "w+"); //address and mode
fprintf(fp, "This is testing for fprintf...\n"); //writing
fputs("This is testing for fputs...\n", fp); //writing
fclose(fp); //close
}
Reading a File
int fgetc( FILE * fp ); //char
char *fgets( char *buf, int n, FILE *fp ); //string
Example Reading
#include <stdio.h>
main() {
FILE *fp;
char buff[255];
fp = fopen("/c/test.txt", "r");
fscanf(fp, "%s", buff);
printf("1 : %s\n", buff );
fgets(buff, 255, (FILE*)fp);
printf("2: %s\n", buff );
fgets(buff, 255, (FILE*)fp);
printf("3: %s\n", buff );
fclose(fp);
}
/* Result */
1: This
2: is testing for fprintf...
3: This is testing for fputs...
First,fscanf()
read just This because after that, it encountered a space.
second call is for fgets()
which reads the remaining line till it encountered end of line(\n).
Finally, the last call fgets()
reads the second line completely.
Binary I/O Functions
size_t fread(void *ptr,
size_t size_of_elements,
size_t number_of_elements,
FILE *a_file);
size_t fwrite(const void *ptr,
size_t size_of_elements,
size_t number_of_elements,
FILE *a_file);
PS: 以上笔记整理至: C - File I/O