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

23 PPSC Unit 4 FILEOperations

Uploaded by

satyamdubey21096
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

23 PPSC Unit 4 FILEOperations

Uploaded by

satyamdubey21096
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 33

School of Computing Science and Engineering

Name: Programming for Problem Solving-C


Couse Code: R1UC101B

Unit 4-File Handling

Name of the Faculty: K Prabu


Program Name:B.Tech(CSE) 1
What is File Handling:
File handling is the storage of data in a file using a
program. In C programming language, the programs store
results, and other program data to a file using file
handling in C.
Also, we can extract/fetch data from a file to work with it in
the program.
The operations that you can perform on a File in C are −
• Creating a new file
• Opening an existing file
• Reading data from an existing file
• Writing data to a file
• Moving data to a specific location on the file
• Closing the file

2
Creating or opening file using
fopen()

• The fopen() function creates a new file or opens an


existing one in C. The fopen function is defined in
the stdio.h header file.
• Now, lets see the syntax for creation of a new file or
opening a file.

file=fopen(“file_name,” “mode”)

3
Basic operations on a file
• Open
• Read
• Write
• Close

Mainly we want to do read or write, but a file has to


be opened before read/write, and should be closed
after all read/write is over

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

• FILE * is a datatype used to represent a pointer to a


file
• fopen takes two parameters, the name of the file to
open and the mode in which it is to be opened
• It returns the pointer to the file if the file is opened
successfully, or NULL to indicate that it is unable to
open the file

10
Example: opening file.dat for
write
FILE *fptr;

fptr = fopen ("file2.dat","w");

if (fptr == NULL) {

printf (“ERROR IN FILE CREATION”);

/* 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

• Sometimes error checking means we want an emergency exit from a


program
• Can be done by the exit() function
• The exit() function, called from anywhere in your C program, will
terminate the program at once

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

• fscanf() works like scanf(), except that its first


argument is a file pointer. The remaining two
arguments are the same as scanf
• The behaviour is exactly the same, except
• The reading is done from the file instead of from the
keyboard (think as if you typed the same thing in the file
as you would in the keyboard for a scanf with the same
arguments)
• The end-of-file for a text file is checked differently (check
against special character EOF)

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

• Takes three parameters


• a character array str, maximum number of characters to
read size, and a file pointer fp
• Reads from the file fp into the array str until any one of
these happens
• No. of characters read = size - 1
• \n is read (the char \n is added to str)
• EOF is reached or an error occurs
• ‘\0’ added at end of str if no error
• Returns NULL on error or EOF, otherwise returns
pointer to str
21
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

• Should close a file when no more read/write to a


file is needed in the rest of the program
• File is closed using fclose() and the file pointer

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?

• Recall that main() is also a function


• It can also take parameters, just like other C function
• The items in the command line are passed as parameters to main
• Parameters argc and argv in main keeps track of the items specified in
the command line

29
How to access them?
int main (int argc, char *argv[]);

Argument Array of strings


Count as command line
arguments including
the command itself.

The parameters are filled up with the command line


arguments typed when the program is run
They can now be accessed inside main just like any
other variable
30
Example: Contd.

$ ./a.out s.dat d.dat

argc=3
./a.out
s.dat
d.dat
argv

argv[0] = “./a.out” argv[1] = “s.dat” argv[2] = “d.dat”

31
Contd.

• Still there is a problem


• All the arguments are passed as strings in argv[ ]
• But the intention may have been to pass an int/float etc.
• Solution: Use sscanf()
• Exactly same as scanf, just reads from a string (char *)
instead of from the keyboard
• The first parameter is the string pointer, the next two
parameters are exactly the same as scanf

32
Example
• Write a program that takes as command line
arguments 2 integers, and prints their sum

int main(int argc, char *argv[ ])


{ $ ./a.out 32 54
int i, n1, n2;
printf(“No. of arg is %d\n”, argc); No. of arg is 3
for (i=0; i<argc; ++i) ./a.out
printf(“%s\n”, argv[i]);
32
sscanf(argv[1], “%d”, &n1);
sscanf(argv[2], “%d”, &n2); 54
printf(“Sum is %d\n”, n1 + n2); Sum is 86
return 0;
} 33

You might also like