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

File Handling in C Second

This document discusses file handling functions in C for writing to and reading from files. It covers formatted and direct output/input functions like fprintf(), fputc(), fputs(), fwrite(), fscanf(), fgetc(), fgets(), and fread(). Example code is provided to demonstrate the usage of each function, including opening, writing to, reading from, and closing files in C. Key aspects like syntax, arguments, and return values are explained for each file handling function.

Uploaded by

LEESHMA
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)
44 views

File Handling in C Second

This document discusses file handling functions in C for writing to and reading from files. It covers formatted and direct output/input functions like fprintf(), fputc(), fputs(), fwrite(), fscanf(), fgetc(), fgets(), and fread(). Example code is provided to demonstrate the usage of each function, including opening, writing to, reading from, and closing files in C. Key aspects like syntax, arguments, and return values are explained for each file handling function.

Uploaded by

LEESHMA
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/ 42

File handling in c

Slide no : 2
Writing to a File:

1. Formatted output functions for file - fprintf()

2. Character output functions for file - fputc() , fputs()

3. Direct output functions - fwrite()


Reading from a File:

1. Formatted input functions for file - fscanf()

2.Character input functions for file - fgetc() , fgets()

3.Direct input function - fread() ,


Change the position of the file indicator

1. fseek()

2. rewind()

3. ftell()
Writing to a File:
fprintf()
• The fprintf function is used to write the formatted data to the stream pointed to by stream. The
arguments of fprintf function are similar to the printf function except that fprintf has an extra
argument which is a file pointer (first argument). This file pointer tells the file where the formatted
output will be written.

• Note: In fprintf, if there are insufficient arguments for the format, the behavior is undefined.

• Syntax of fprintf():

int fprintf(FILE * restrict stream, const char * restrict format, ...);

• Return value of fprintf():

• On success, fprintf function returns the total number of characters written (transmitted)and on
error return a negative number.
Example code to explain the working of fprintf function

#include <stdio.h> //three times asking for


int main() //student name
{ for (i=1 ; i<4 ; i++)
//file pointer {
FILE *fp = NULL; puts ("Enter the student name: ");
int i = 0; //Get input from the user
char name[40] = {0}; gets (name);
//create a text file //Write formatted data into the file
fp = fopen ("aticleworld.txt", "w"); fprintf (fp, "%d. Name = [%s]\n",i,name);
if(fp == NULL) }
{ //close the file
printf("File is not created\n"); fclose(fp);
exit(1); return 0;
} }
fputc():

The fputc() function writes the character (unsigned char) to the output stream, at the specified
position (indicated by the associated file position indicator) and then advances the indicator
appropriately.
Syntax of fputc()
int fputc(int c, FILE *stream);

Return value of fputc():


If fputc has written the character successfully, then return the written character. If there is any error,
then it returns EOF.
Example code for fputc

#include <stdio.h>
int main()
{
int ch = 0;
FILE *fp = NULL;
fp = fopen("aticleworld.txt", "w");
if(fp == NULL)
{
printf("Error in creating the file\n");
exit(1);
}
//Write A to Z in file
for(ch =65 ; ch <= 90 ; ++ch)
{
fputc(ch, fp);
}
//close the file
fclose(fp);
printf("A t0 Z written to the created file\n");
return 0;
}
fputs()
The fputs function writes the string pointed to the output stream. The terminating null
character is not written to the file. It takes two argument pointer to string and file pointer.

Syntax of fputs
int fputs(const char * restrict s, FILE * restrict stream);

Return value of fputs():


On success, the fputs function returns a non-negative value and if a write error occurs,
then returns EOF.
#include <stdio.h>
int main()
{
//file pointer
FILE *fp = NULL;
fp = fopen("aticleworld.txt", "w");
if(fp == NULL)
{
printf("Error in creating the file\n");
exit(1);
}
fputs("Hello There, I hope this article will help!",fp);
fclose(fp);
printf("File has been created successfully\n");
return 0;
}
fwrite():

The fwrite function writes n numb elements from the given array to the output stream.
for each object fputc is called size times (count of bytes for a single element) and file position indicator for the
stream is advanced by the number of characters written.
Syntax of fwrite():
size_t fwrite(const void * restrict ptr, size_t size, size_t nmemb,FILE * restrict stream);
Where,
ptr: Pointer to the array of elements to be written.
size: Size in bytes of each element to be written.
nmemb: Number of elements to be written.
stream: Pointer to the file, where data will be written.

Return value of fwrite():


On success, it returns the number of elements successfully written. On error, it returns a number of elements less than
nmemb.
#include <stdio.h>
#define MAX_SIZE 32
int main()
{ FILE *fp = NULL;
char buffer[MAX_SIZE] = {0};
printf("Enter your Name = ");
fgets(buffer,MAX_SIZE,stdin);
fp = fopen("aticleworld.txt", "w");
if(fp == NULL)
{ printf("Error in creating the file\n");
exit(1);
}
fwrite(buffer, sizeof(buffer[0]), MAX_SIZE, fp);
fclose(fp);
printf("File has been created successfully\n");
return 0;
Reading from a File:
fscanf():

The fscanf function is used to read the formatted data from the stream pointed to by stream. The arguments of
fscanf function are similar to the scanf function except that fscanf has an extra argument which is a file pointer
(first argument). This file pointer tells the file from the formatted input will be read.
Syntax of fscanf():
int fscanf(FILE * restrict stream, const char * restrict format, ...);

Note: In fscanf, if there are insufficient arguments for the format, the behavior is undefined.

Return value of fscanf():


On success, fscanf function returns the total number of input read and on error or at the end of the file return
EOF.
#include <stdio.h>
#define MAX_SIZE 32
int main()
{ FILE *fp = NULL;
char readFileData[MAX_SIZE+MAX_SIZE] = {0};
fp = fopen("aticleworld.txt", "r");
if(fp == NULL)
{ printf("Error in creating the file\n");
exit(1);
}
fscanf(fp,"%s",readFileData);
puts(readFileData);
fclose(fp);
printf("Read file successfully\n");
return 0;
}
2.Character input functions for file
fgetc():
The fgetc() function read a single character from the stream and return their ASCII value. After
reading the character, it advances the associated file position indicator for the stream.
Syntax of fgetc():
int fgetc(FILE *stream);

Return value of fgetc():


On success, it returns the ASCII value of the character. On error or end of the file, it returns EOF.
#include <stdio.h>
int main()
{
int ch = 0;
FILE *fp = NULL;
fp = fopen("aticleworld.txt", "r");
if(fp == NULL)
{
printf("Error in opening the file\n");
exit(1);
}
while( (ch=fgetc(fp)) != EOF )
{
printf("%c", ch);
}
fclose(fp);
printf("\n\n\nRead file successfully\n");
return 0;
}
fgets():

The fgets function reads characters from the specified stream and store into the character array.
It reads only n-1 character, where n is the specified number of characters.
It stops the reading when read newline character or (n-1) character, or encounter end-of-file. The good thing is that it
writes null character just after written the last character into the array.
Syntax of fgets:
char *fgets(char * restrict s, int n,FILE * restrict stream);

Return value of fgets():


On success, the fgets function returns the string (same s parameter). On error return null pointer.
Note: If end-of-file is encountered and no characters have been read into the “s” (character array), the contents of the
“s” remain unchanged and a null pointer is returned.
#include <stdio.h>
#define MAX_SIZE 32
int main()
{
FILE *fp = NULL;
char readFileData[MAX_SIZE] = {0};
fp = fopen("aticleworld.txt", "r");
if(fp == NULL)
{
printf("Error in opening the file\n");
exit(1);
}
if(fgets(readFileData,MAX_SIZE,fp) == NULL)
{
printf("Error in reading the file\n");
fclose(fp);
exit(1);
}
puts(readFileData);
fclose(fp);
printf("Read file successfully\n");
return 0;
}
fread():
The fread function reads nmemb elements from the given stream to the given array.
for each element, fgetc is called size times (count of bytes for a single element) and file
position indicator for the stream is advanced by the number of characters read.
Syntax of fread:
size_t fread(void * restrict ptr, size_t size, size_t nmemb,
FILE * restrict stream);
Where,
ptr: Pointer to a block of memory with a minimum size of size*nmemb bytes.
size: Size in bytes of each element to be read.
nmemb: Number of elements to be read.
stream: Pointer to the file, from where data will be read.
Return value of fread():
On success, it returns the number of elements successfully read. On error, it returns a number of elements less than nmemb.
#include <stdio.h>
#define MAX_SIZE 32
int main()
{ FILE *fp = NULL;
char readFileData[MAX_SIZE] = {0};
fp = fopen("aticleworld.txt", "r");
if(fp == NULL)
{ printf("Error in opening the file\n");
exit(1);
}
fread(readFileData,sizeof(char),6, fp);
puts(readFileData);
fclose(fp);
printf("Read file successfully\n");
return 0;
}
Question 1

Your program should read integers from an input file named "input.txt," perform some
calculations on these integers, and then write the results to an output file named
"output.txt."

1.Open the "input.txt" file for reading and "output.txt" file for writing.
2.Read a series of integers from the "input.txt" file until the end of the file is reached.
3.For each integer read, calculate its square and store the result in a separate variable.
4.Write the original integer and its square (separated by a space) to the "output.txt" file for each integer
read from the input file.
5.Close both the input and output files when done.
Change the position of the file indicator
fseek():

The fseek function sets the file position indicator of the stream to the given offset. Three-position (whence)
are given for the fseek, these are SEEK_SET (Beginning of file), SEEK_CUR (Current position of the
file pointer), and SEEK_END (End of file). The new position of file indicator is obtained by adding offset
to the position specified by whence.
Syntax of fseek():
int fseek(FILE *stream, long int offset, int whence);
Where,
stream: Stream which position indicator will change.
offset: This is the number of bytes to offset from whence.
whence: position from where the offset is added. It is specified by one of the following constants,
SEEK_SET, SEEK_CUR or SEEK_END.
Return value of fseek():
On success, it returns the zero. On error, it returns a non-zero number.
#include <stdio.h>
int main()
{
FILE *fp = NULL;
int ch =0;
fp = fopen("aticleworld.txt", "r");
if(fp == NULL){
printf("Error in opening the file\n");
exit(1);
}
fseek( fp,1, SEEK_SET );
ch = fgetc(fp);
printf(" %c\n", ch);
fclose(fp);
return 0;
}
rewind()

The rewind function sets the file position indicator to the beginning of the file. It equivalent to
(void)fseek(stream, 0L, SEEK_SET).

Syntax of rewind():
void rewind(FILE *stream);

Return value of rewind():


The rewind function returns no value.
ftell():
The ftell function returns the current value of the file position indicator for the given stream.
Syntax of ftell():
long int ftell(FILE *stream);

Return value of ftell():


On success, it returns the current value of the file position indicator for the stream. On error, it
returns −1L and stores an implementation-defined positive value in errno.
What should be the output of this program?

#include "stdio.h"

int main()
{
FILE *fp;
char c[1024];

// "Kernighan and Ritchie"


fp = fopen("test.txt", "r");

c[0] = getc(fp);
fseek(fp, 0, SEEK_END);
fseek(fp, -7L, SEEK_CUR);
fgets(c, 6, fp);
puts(c);
return 0;
}
Ritch
Q. What is the output of this program?
#include <stdio.h>
int main(){
FILE *fp;
char *str;
fp=fopen("demo.txt","r");// demo.txt :you are a good
programmer
while(fgets(str,6,fp)!=NULL)
puts(str);
fclose(fp);
return 0;
}
e a good programmer
What is the output of this program?

#include <stdio.h>
int main(){
char c;
FILE *fp;
fp=fopen("demo.txt","r");
while((c=fgetc(fp))!=EOF)
printf("%c",c);
fclose(fp);
return 0;
}
It will print the content of file demo.txt
What is the output of this program?

#include <stdio.h>
int main(){
char c;
FILE *fp;
fp=fopen("demo.txt","a+"); // demo.txt : hello you are reading a file
fprintf(fp," demo");
fclose(fp);
fp=fopen("myfile.txt","r");

while((c=fgetc(fp))!=EOF)
printf("%c",c);
fclose(fp);
return 0;
}
hello you are reading a file demo
"r+" (Read and Write):
• "r+" mode is used to open a file for both reading and writing.
• If the file exists, it is opened, and you can both read from and write to
it.
• If the file does not exist, attempting to open it in "r+" mode will result
in an error.
#include <stdio.h>
// Read data from the file
int main() {
fgets(data, sizeof(data), file);
FILE *file;
printf("Read from file: %s", data);
char data[100];

// Write data to the file


// Open an existing file for reading and writing
fputs("This is new content.", file);
file = fopen("example.txt", "r+");

// Close the file


if (file == NULL) {
fclose(file);
perror("Error opening file");
return 1;
return 0;
}
}
"w+" (Write and Read):

• "w+" mode is used to open a file for both writing and reading.

• If the file exists, it is truncated (its contents are deleted), and you can both

read from and write to it.

• If the file does not exist, a new empty file is created.


#include <stdio.h>
// Move the file pointer to the beginning
int main() {
rewind(file);
FILE *file;
char data[100];
// Read data from the file
fgets(data, sizeof(data), file);
// Open or create a file for writing and reading
printf("Read from file: %s", data);
file = fopen("example.txt", "w+");
// Close the file
if (file == NULL) {
fclose(file);
printf("Error opening file");
return 1;
return 0;
}
}
// Write data to the file
fputs("This is some content.", file);
"r+" mode allows you to open a file for both reading and writing.
#include <stdio.h>

int main() {
FILE *file; // Write to the file
fprintf(file, "This is a new line written to the file.\n");
// Open a file named "example.txt" in "r+" mode
file = fopen("example.txt", "r+"); // Close the file
fclose(file);
if (file == NULL) {
printf("Error opening the file.\n"); return 0;
return 1; }
}

// Read from the file


char buffer[100];
if (fgets(buffer, sizeof(buffer), file) != NULL) {
printf("Read from the file: %s", buffer);
} else {
printf("Error reading from the file.\n");
}

You might also like