FILE I O
FILE I O
The state of a file includes its mode (read, write, append, etc.), error state
(EOF, error), and whether it is open or closed. C maintains a status for each
open file in the form of a structure (FILE).
#include <stdio.h>
int main() {
FILE *fp = fopen("nofile.txt", "r");
if (fp == NULL) {
perror("Error opening file");
return 1;
}
fclose(fp);
return 0;
Steps in Processing a File
1. Create the stream via a pointer variable using the
FILE structure:
FILE *fp;
2. Open the file, associating the stream name with
the file name.
3. Read or write the data.
4. Close the file.
The basic file operations are
• fopen - open a file- specify how its opened
(read/write) and type (binary/text)
• fclose - close an opened file
• fread - read from a file
• fwrite - write to a file
• fseek/fsetpos - move a file pointer to somewhere
in a file.
• ftell/fgetpos - tell you where the file pointer is
located.
File Open Modes
Additionally,
Syntax:
FILE *fp = fopen("filename", "mode");
• Modes include "r", "w", "a", "rb", "wb", etc.
Closing: fclose(fp);
• Releases the file and flushes buffers.
File Open
• On success fopen() returns a pointer of type FILE
and
on error it returns NULL.
• We assign the return value of fopen to our
pointer variable:
FILE *fp;
• fp= fopen(“MYFILE.TXT”, “w”);
• fp= fopen(“A:\\DOCUMENTS\\MYFILE.TXT”, “w”);
Errors in fopen
• If an error occurs in opening a file ,then fopen()
returns NULL.
FILE *fp;
fp=fopen(“abc.txt”, ”r”);
if(fp==NULL)
{
printf(“Error in opening file”);
exit(1);
}
Closing a File
• When we finish with a mode, we need to close
the file before ending the program or beginning
another mode with that same file.
• To close a file, we use fclose() and the pointer
variable:
fclose(fp);
File Input/Output Functions
Standard functions from <stdio.h> include:
• Text mode I/O:
– fprintf(fp, format, ...) – write formatted data
– fscanf(fp, format, ...) – read formatted data
– fgets(), fputs(), fgetc(), fputc()
#include <stdio.h>
int main() {
FILE *fp = fopen("fprintf_demo.txt", "w");
if (fp == NULL) {
printf("Error opening file.\n");
return 1;
}
fprintf(fp, "Name: %s\nAge: %d\n", "Alice", 20);
fclose(fp);
Name: Alice
printf("Data written using fprintf().\n"); Age: 20
return 0;
}
fscanf() – Read formatted data from a file
#include <stdio.h>
int main() {
char name[50];
int age;
FILE *fp = fopen("fscanf_demo.txt", "w");
fprintf(fp, "Bob 25");
fclose(fp);
fp = fopen("fscanf_demo.txt", "r");
if (fp == NULL) {
printf("Error opening file.\n");
return 1;
}
fscanf(fp, "%s %d", name, &age);
printf("Name: %s\nAge: %d\n", name, age);
fclose(fp); Name: Bob
Age: 25
return 0;
}
fgets() – Read a line from a file
Reads a string (including spaces) until newline or EOF is found.
#include <stdio.h>
int main() {
char line[100];
FILE *fp = fopen("fgets_demo.txt", "w");
fputs("This is a test line.\nSecond line here.", fp);
fclose(fp);
fp = fopen("fgets_demo.txt", "r");
if (fp == NULL) {
printf("Error opening file.\n");
return 1;
}
fgets(line, sizeof(line), fp);
printf("Line read: %s", line);
fclose(fp); Line read: This is a test line.
return 0;
fputs() – Write a string to a file
Writes a string (without format specifiers) to a file.
#include <stdio.h>
int main() {
FILE *fp = fopen("fputs_demo.txt", "w");
if (fp == NULL) {
printf("Error opening file.\n");
return 1;
}
#include <stdio.h>
int main() {
FILE *fp = fopen("fgetc_demo.txt", "w");
fputs("Hello", fp);
fclose(fp);
fp = fopen("fgetc_demo.txt", "r");
if (fp == NULL) {
printf("Error opening file.\n");
return 1;
}
char ch;
while ((ch = fgetc(fp)) != EOF) {
printf("%c", ch);
}
fclose(fp); Hello
return 0;
fputc() – Write a Single Character to a File
Writes one character at a time to a file.
#include <stdio.h>
int main() {
FILE *fp = fopen("fputc_demo.txt", "w");
if (fp == NULL) {
printf("Error opening file.\n");
return 1;
}
fputc('A', fp);
fputc('B', fp);
fputc('C', fp);
fclose(fp);
#include <stdio.h>
int main() {
FILE *fp = fopen("text.txt", "w");
fprintf(fp, "Name: John\n");
fclose(fp);
char buffer[100];
fp = fopen("text.txt", "r");
fgets(buffer, 100, fp);
printf("Data: %s", buffer);
fclose(fp);
return 0;
}
Binary File Example:
#include <stdio.h>
int main() {
int x = 45;
FILE *fp = fopen("num.dat", "wb");
fwrite(&x, sizeof(x), 1, fp);
fclose(fp);
int y;
fp = fopen("num.dat", "rb");
fread(&y, sizeof(y), 1, fp);
printf("Read: %d", y);
fclose(fp);
return 0;
}
File Status Functions
(Error Handling)
• feof(fp) – returns true if EOF is
reached
• ferror(fp) – checks for an error
• perror() – prints error message
• clearerr(fp) – clears error indicator
Example:
#include <stdio.h>
int main() {
FILE *fp = fopen("data.txt", "r");
if (ferror(fp)) {
perror("Error occurred");
clearerr(fp);
}
fclose(fp);
return 0;
}
Positioning Functions
fseek(fp, offset, origin) – moves pointer
ftell(fp) – returns current file position
rewind(fp) – resets pointer to beginning
#include <stdio.h>
int main() {
FILE *fp = fopen("seekdemo.txt", "w+");
fputs("abcdef", fp);
fseek(fp, 3, SEEK_SET);
fputc('X', fp); // Replaces 'd' with 'X'
rewind(fp);
char ch;
while ((ch = fgetc(fp)) != EOF)
putchar(ch); // Output: abcXef
fclose(fp);
return 0;
}
Command Line Arguments
Allow you to pass parameters to main() during execution.
int main(int argc, char *argv[])
argc: Number of arguments argv[]: Argument strings
#include <stdio.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s <filename>\n", argv[0]);
return 1;
}
FILE *fp = fopen(argv[1], "r");
if (fp == NULL) {
perror("Error opening file");
return 1;
}
char ch;
while ((ch = fgetc(fp)) != EOF)
putchar(ch);
fclose(fp);
return 0;
}