C Language | Advanced Features | Files and Streams - fopen(), fclose(), fflush(), and More
The C standard library provides stream functions for reading and writing files.
Opening and Closing Files
Use a FILE * stream declared in stdio.h.
FILE *fopen(const char *filename, const char *mode);
int fclose(FILE *stream);
int fflush(FILE *stream);
| Mode | Meaning |
|---|---|
"r" |
read an existing file |
"w" |
create or truncate a file for writing |
"a" |
append, creating the file if needed |
"r+" |
read and write an existing file |
"w+" |
create or truncate a file for reading and writing |
"a+" |
read and append |
fopen() returns NULL on failure. fclose() closes the stream and flushes buffered output. Call fflush() when buffered output must be written immediately.
Code 1
#include <stdio.h>
int main() {
FILE *file = fopen("test.txt" , "r");
if (file == NULL) {
printf("Could not open test.txt.\n");
return 1;
}
fclose(file);
return 0;
}
Reading and Writing Characters
Use fgetc() and fputc() for individual characters.
int fgetc(FILE *stream);
int fputc(int character, FILE *stream);
fgetc() returns EOF at the end of a file or on error. Use feof() and ferror() to distinguish the conditions.
Code 2
#include <stdio.h>
int main() {
FILE *file = fopen("test.txt" , "r");
int value;
if (file == NULL) return 1;
while((value = fgetc(file)) != EOF)
printf("%c" , value);
if (ferror(file)) printf("A stream error occurred.\n");
fclose(file);
return 0;
}
Reading and Writing Lines
Use fgets() and fputs() for text lines.
char *fgets(char *buffer, int size, FILE *stream);
int fputs(const char *text, FILE *stream);
Code 3
#include <stdio.h>
#define BUFFER_SIZE 1024
int main() {
FILE *input = fopen("in.txt" , "r");
FILE *output = fopen("out.txt" , "w");
char line[BUFFER_SIZE];
if (input == NULL || output == NULL) return 1;
while(fgets(line , BUFFER_SIZE , input) != NULL)
fputs(line , output);
fclose(input);
fclose(output);
return 0;
}
This program copies a text file one line at a time.