File I/O In C
- Required library:
<stdio.h>
FILE
struct is a specific pointer type held by the standard I/O library.
Reading A File
Open a file with the function: fopen(char *filename, char *mode)
and read from it using fscanf
, fgets
. Once done, you should close the file using fclose(filePointer)
.
fscanf
is not recommended since it has conflicts with buffer sizes and undefined behavior - same reason to not use scanf
.
char *buffer = malloc(sizeof(char) * 30);
FILE *fp = open("myfile.txt", "r");
fgets(buffer, 30, fp);
fclose(fp);
free(buffer);
Writing To A File
Open a file with the function: fopen(char *filename, char *mode)
and write to it using fprintf
, fputs
. You can flush the write buffer by running fflush(filePointer)
. Once done, you should close the file using fclose(filePointer)
.
FILE *fp = open("myfile.txt", "w");
fputs("this is a new line\n", fp);
fclose(fp);