0% found this document useful (0 votes)
3 views

FILE I O

The document explains the concept of files in computer systems, detailing the differences between text and binary files, and the various operations for file handling in C, including opening, closing, reading, and writing files. It covers file modes, error handling, and positioning functions, as well as command line arguments for file processing. Examples of file input/output functions and their usage in C programming are provided throughout the document.

Uploaded by

5377696raghav10
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

FILE I O

The document explains the concept of files in computer systems, detailing the differences between text and binary files, and the various operations for file handling in C, including opening, closing, reading, and writing files. It covers file modes, error handling, and positioning functions, as well as command line arguments for file processing. Examples of file input/output functions and their usage in C programming are provided throughout the document.

Uploaded by

5377696raghav10
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 28

File

File Input and Output – Concept of a file, text


files and binary files, Differences between text
and binary files, State of a file, Opening and
Closing files, file input/output functions
(standard library input/output functions for
files), file status functions (error handling),
Positioning functions.
Command line arguments.
What is a File?
• A file is a collection of related data that a
computers treats as a single unit.
• Computers store files to secondary storage so
that the contents of files remain intact when a
computer turns off.
• When a computer reads a file, it copies the file
from the storage device to memory; when it
writes to a file, it transfers data from memory to
the storage device.
• C uses a structure called FILE (defined in stdio.h)
to store the attributes of a file.
Text Files and Binary Files
Text Files: Store data in readable characters.
Example: .txt, .csv. Data is stored as a sequence of
ASCII characters.

Binary Files: Store data in raw byte format


(machine-readable). Example: .dat, .exe. More
efficient for storing structured data like arrays,
structures, etc.
Differences Between Text and Binary Files
State of a File

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,

• “r+” (read + write) In this mode we can also write


and modify existing data .The file to be opened
must exist and the previous data of file is not
erased . This mode is also called update mode.
• “w+“(write + read) If the file doesn’t exist then a
new file is created and if the file exists than the
previous data is erased.
• “a+”(append + read) In this mode we can append
as well as read the existing file .
File Open
• The file open function (fopen) serves two purposes:
– It makes the connection between the physical file
and the stream.
– It creates “a program file structure to store the
information” .

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()

• Binary mode I/O:


• fread(ptr, size, count, fp)
• fwrite(ptr, size, count, fp)
fprintf()
Syntax:
fprintf (fp,"string",variables);
Used to write formatted output to a file (similar to printf).

#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;
}

fputs("Hello from fputs()!\n", fp);


fclose(fp);

printf("String written using fputs().\n"); Hello from fputs()!


return 0;
}
fgetc() – Read a single character from a file
Reads one character at a time from the file.

#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);

printf("Characters written using fputc().\n"); ABC


return 0;
Text File Example:

#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;
}

You might also like