File Handling in C Second
File Handling in C Second
Slide no : 2
Writing to a File:
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():
• 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
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);
#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);
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.
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.
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);
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);
#include "stdio.h"
int main()
{
FILE *fp;
char c[1024];
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];
• "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
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; }
}