File Handling in C
File Handling in C
Concept of files
Files
File – place on disc where group of related data is
stored
E.g. your C programs, executables
fp = fopen(“filename”, “mode”);
/*opens file with name filename , assigns identifier to fp */
fp
contains all information about file
Communication link between system and program
Mode can be
r open file for reading only
w open file for writing only
a open file for appending (adding) data
Different modes
Writing mode
if file already exists then contents are deleted,
else new file with specified name created
Appending mode
if file already exists then file opened with contents safe
else new file created
Reading mode
if file already exists then opened with contents safe
else error occurs.
Ensures
All outstanding information associated with file flushed
out from buffers
All links to file broken
Accidental misuse of file prevented
Example:
putw(num,fp);
fclose(fp);
}
Output :
Data in file...
78
45
63
Another C program using getw, putw
#include <stdio.h>
main()
{ int i,sum1=0;
FILE *f1;
/* open files */
f1 = fopen("int_data.bin","w");
/* write integers to files in binary and text format*/
for(i=10;i<15;i++)
putw(i,f1);
fclose(f1);
f1 = fopen("int_data.bin","r");
while((i=getw(f1))!=EOF)
{ sum1+=i;
printf("binary file: i=%d\n",i);
} /* end while getw */
printf("binary sum=%d,sum1);
fclose(f1);
}
fgets()
#include <stdio.h>
#define MAX 15
int main()
{
char buf[MAX];
fgets(buf, MAX, stdin);
printf("string is: %s\n", buf);
return 0;
}
Output
Input:
Hello and welcome to GeeksforGeeks
Output:
Hello and welc
Fputs()
int fputs(const char *str, FILE *stream)
Parameters
str − This is an array containing the null-terminated
sequence of characters to be written.
stream − This is the pointer to a FILE object that
identifies the stream where the string is to be written.
Return Value
This function returns a non-negative value, or else on
error it returns EOF.
C program to illustrate
#include <stdio.h>
int main () {
FILE *fp;
fp = fopen("file.txt", "w+");
fputs("This is c programming.", fp);
fputs("This is a system programming language.", fp);
fclose(fp);
return(0);
}
Output
This is c programming.This is a system programming
language.