23 PPSC Unit 4 FILEOperations
23 PPSC Unit 4 FILEOperations
2
Creating or opening file using
fopen()
file=fopen(“file_name,” “mode”)
3
Basic operations on a file
• Open
• Read
• Write
• Close
4
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *file;
char data[100];
// 1. Create and Write to a File
file = fopen("example.txt", "w");
if (file == NULL) {
printf("Error opening file for writing!\n");
return 1;
}
fprintf(file, "Hello, this is a sample text.\n");
fprintf(file, "File handling in C is easy.\n");
fclose(file);
printf("Data written to file successfully.\n"); 5
// 2. Read from the File
file = fopen("example.txt", "r");
if (file == NULL) {
printf("Error opening file for reading!\n");
return 1;
}
printf("\nReading data from file:\n");
while (fgets(data, sizeof(data), file) != NULL) {
printf("%s", data);
}
fclose(file);
6
// 3. Append to the File
file = fopen("example.txt", "a");
if (file == NULL) {
printf("Error opening file for appending!\n");
return 1;
}
fprintf(file, "Appending new data to the file.\n");
fclose(file);
printf("\nData appended to file successfully.\n");
7
// 4. Read the Updated File
file = fopen("example.txt", "r");
if (file == NULL) {
printf("Error opening file for reading updated content!\n");
return 1;
}
printf("\nReading updated data from file:\n");
while (fgets(data, sizeof(data), file) != NULL) {
printf("%s", data);
}
fclose(file);
return 0;
}
8
Organization of a file
• Stored as a sequence of bytes, logically contiguous
• May not be physically contiguous on disk, but you do not
need to worry about that
• The last byte of a file contains the end-of-file character
(EOF), with ASCII code 1A (hex).
• While reading a text file, the EOF character can be
checked to know the end
• Two kinds of files:
• Text : contains ASCII codes only
• Binary : can contain non-ASCII characters
• Example: Image, audio, video, executable, etc.
• EOF cannot be used to check the end of file
9
Opening a File: fopen()
10
Example: opening file.dat for
write
FILE *fptr;
if (fptr == NULL) {
/* CODE */
}
11
Modes for opening files
• The second argument of fopen is the mode in which
we open the file.
12
Modes for opening files
• The second argument of fopen is the mode in which
we open the file.
• "r" : opens a file for reading (can only read)
• Error if the file does not already exists
• "r+" : allows write also
13
Modes for opening files
• The second argument of fopen is the mode in which
we open the file.
• "r" : opens a file for reading (can only read)
• Error if the file does not already exists
• "r+" : allows write also
• "w" : creates a file for writing (can only write)
• Will create the file if it does not exist
• Caution: writes over all previous contents if the flle
already exists
• "w+" : allows read also
14
Modes for opening files
• The second argument of fopen is the mode in which
we open the file.
• "r" : opens a file for reading (can only read)
• Error if the file does not already exists
• "r+" : allows write also
• "w" : creates a file for writing (can only write)
• Will create the file if it does not exist
• Caution: writes over all previous contents if the flle
already exists
• "w+" : allows read also
• "a" : opens a file for appending (write at the end
of the file)
• "a+" : allows read also
15
The exit() function
16
Usage of exit( )
FILE *fptr;
char filename[]= "file2.dat";
fptr = fopen (filename,"w");
if (fptr == NULL) {
printf (“ERROR IN FILE CREATION”);
/* Do something */
exit(-1);
}
………rest of the program………
17
Writing to a file: fprintf( )
• fprintf() works exactly like printf(), except that its
first argument is a file pointer. The remaining two
arguments are the same as printf
• The behaviour is exactly the same, except that the
writing is done on the file instead of the display
FILE *fptr;
fptr = fopen ("file.dat","w");
fprintf (fptr, "Hello World!\n");
fprintf (fptr, “%d %d”, a, b);
18
Reading from a file: fscanf( )
19
Reading from a file: fscanf( )
FILE *fptr;
EOF checking in a loop
fptr = fopen (“input.dat”, “r”);
/* Check it's open */ char ch;
if (fptr == NULL) while (fscanf(fptr, “%c”,
{ &ch) != EOF)
printf(“Error in opening file \n”); {
exit(-1);
/* not end of file; read */
}
fscanf (fptr, “%d %d”,&x, &y); }
20
Reading lines from a file: fgets()
FILE *fptr;
char line[1000];
/* Open file and check it is open */
while (fgets(line,1000,fptr) != NULL)
{
printf ("Read line %s\n",line);
}
22
Writing lines to a file: fputs()
• Takes two parameters
• A string str (null terminated) and a file pointer fp
• Writes the string pointed to by str into the file
• Returns non-negative integer on success, EOF on error
23
Reading/Writing a character:
fgetc(), fputc()
• Equivalent of getchar(), putchar() for reading/writing
char from/to keyboard
• Exactly same, except that the first parameter is a file
pointer
• Equivalent to reading/writing a byte (the char)
int fgetc(FILE *fp);
int fputc(int c, FILE *fp);
• Example:
char c;
c = fgetc(fp1); fputc(c, fp2);
24
Formatted and Un-formatted I/O
• Formatted I/O
• Using fprintf/fscanf
• Can specify format strings to directly read as integers, float
etc.
• Unformatted I/O
• Using fgets/fputs/fgetc/fputc
• No format string to read different data types
• Need to read as characters and convert explicitly
25
Closing a file
FILE *fptr;
char filename[]= "myfile.dat";
fptr = fopen (filename,"w");
fprintf (fptr,"Hello World of filing!\n");
…. Any more read/write to myfile.dat….
fclose (fptr);
26
Command Line
Arguments
27
What are they?
• A program can be executed by directly typing a
command with parameters at the prompt
$ cc –o test test.c
$ ./a.out in.dat out.dat
$ prog_name param_1 param_2 param_3 ..
• The individual items specified are separated from one another by spaces
• First item is the program name
28
What do they mean?
29
How to access them?
int main (int argc, char *argv[]);
argc=3
./a.out
s.dat
d.dat
argv
31
Contd.
32
Example
• Write a program that takes as command line
arguments 2 integers, and prints their sum