As with any OS, file handling is a core concept in Linux. Any system programmer would learn it as one of his/her initial programming assignments. This aspect of programming involves system files.
Through file handling, one can perform operations like create, modify, delete etc on system files. Here in this article I try to bring in the very basic of file handling. Hope this article will clear the top layer of this multilayer aspect.
File handling functions
In this article, we will cover the following functions that are popularly used in file handling :
fopen()
FILE *fopen(const char *path, const char *mode);
The fopen() function is used to open a file and associates an I/O stream with it. This function takes two arguments. The first argument is a pointer to a string containing name of the file to be opened while the second argument is the mode in which the file is to be opened. The mode can be :
- ‘r’ : Open text file for reading. The stream is positioned at the beginning of the file.
- ‘r+’ : Open for reading and writing. The stream is positioned at the beginning of the file.
- ‘w’ : Truncate file to zero length or create text file for writing. The stream is positioned at the beginning of the file.
- ‘w+’ : Open for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file.
- ‘a’ : Open for appending (writing at end of file). The file is created if it does not exist. The stream is positioned at the end of the file.
- ‘a+’ : Open for reading and appending (writing at end of file). The file is created if it does not exist. The initial file position for reading is at the beginning of the file, but output is always appended to the end of the file.
The fopen() function returns a FILE stream pointer on success while it returns NULL in case of a failure.
fread() and fwrite()
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream); size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
The functions fread/fwrite are used for reading/writing data from/to the file opened by fopen function. These functions accept three arguments. The first argument is a pointer to buffer used for reading/writing the data. The data read/written is in the form of ‘nmemb’ elements each ‘size’ bytes long.
In case of success, fread/fwrite return the number of bytes actually read/written from/to the stream opened by fopen function. In case of failure, a lesser number of byes (then requested to read/write) is returned.
fseek()
int fseek(FILE *stream, long offset, int whence);
The fseek() function is used to set the file position indicator for the stream to a new position. This function accepts three arguments. The first argument is the FILE stream pointer returned by the fopen() function. The second argument ‘offset’ tells the amount of bytes to seek. The third argument ‘whence’ tells from where the seek of ‘offset’ number of bytes is to be done. The available values for whence are SEEK_SET, SEEK_CUR, or SEEK_END. These three values (in order) depict the start of the file, the current position and the end of the file.
Upon success, this function returns 0, otherwise it returns -1.
fclose()
int fclose(FILE *fp);
The fclose() function first flushes the stream opened by fopen() and then closes the underlying descriptor. Upon successful completion this function returns 0 else end of file (eof) is returned. In case of failure, if the stream is accessed further then the behavior remains undefined.
The code
#include<stdio.h> #include<string.h> #define SIZE 1 #define NUMELEM 5 int main(void) { FILE* fd = NULL; char buff[100]; memset(buff,0,sizeof(buff)); fd = fopen("test.txt","rw+"); if(NULL == fd) { printf("\n fopen() Error!!!\n"); return 1; } printf("\n File opened successfully through fopen()\n"); if(SIZE*NUMELEM != fread(buff,SIZE,NUMELEM,fd)) { printf("\n fread() failed\n"); return 1; } printf("\n Some bytes successfully read through fread()\n"); printf("\n The bytes read are [%s]\n",buff); if(0 != fseek(fd,11,SEEK_CUR)) { printf("\n fseek() failed\n"); return 1; } printf("\n fseek() successful\n"); if(SIZE*NUMELEM != fwrite(buff,SIZE,strlen(buff),fd)) { printf("\n fwrite() failed\n"); return 1; } printf("\n fwrite() successful, data written to text file\n"); fclose(fd); printf("\n File stream closed through fclose()\n"); return 0; }
The code above assumes that you have a test file “test.txt” placed in the same location from where this executable will be run.
Initially the content in file is :
$ cat test.txt hello everybody
Now, run the code :
$ ./fileHandling File opened successfully through fopen() Some bytes successfully read through fread() The bytes read are [hello] fseek() successful fwrite() successful, data written to text file File stream closed through fclose()
Again check the contents of the file test.txt. As you see below, the content of the file was modified.
$ cat test.txt hello everybody hello
Comments on this entry are closed.
Hi,
Deeply, thanks a lot
very nice article and i sent it to my students in university
This is not really reading a file, it reading an ITEM. A file contains items. So a Directory is more appropriately called a file and all items with in it, including other Directories are Items. I worked on the Pick System. That system READs and ITEM.
To access the file you would Open filename to filenamevariable. If the file doesn’t exist the Open statement fails and it is up to the programmer to resolve via error coding; e.g. Create the file.
When you want an item you READ item FROM filenamevariable THEN.
If the item doesn’t exist, then once again the programmer has to resolve error.
So in closing it would go something like this;
The id would be supplied by user or via a select list (another story altogether)
open “Invoices” to Invf then
read item from Invf, id else item=””
do whatever you need to do with the item by referencing a specific attributes (fields)
When done
write item on invf, id
end
When the program ends the file is closed automatically.
Let the flames begin.. lol
I need a c++ file handling solution under linux , using gcc.
Thank’s . Regards.
for good formatting, adding newline after calling the fwrite function
fprintf(fd,”\n”);
Are you certain of the following:
“In case of success, fread/fwrite return the number of bytes actually read/written from/to the stream opened by fopen function. In case of failure, a lesser number of byes (then requested to read/write) is returned.”
If gcc lib is used then fread returns the block count not the number of bytes read.
This also means that if EOF is reached that the partial block is dropped, not returned.
fread will only return the bytes read if the block size is 1, so:
blockRead = fread(blocks, 1, blockMax, file)
http://www.gnu.org/software/libc/manual/html_mono/libc.html#Block-Input_002fOutput
Or perhaps your using a different fread?
really thanxxx your article help me alott in my project work…..!!!!
nice article
There is no fwrite function to add the second line of text.
Thanks to all devloper who devlop this website , i like and i gane knowledge about file handling in c , it’s very helpful in my first mca sem c project. i agai say thanks………….
kamlesh
//THIS PROGRAM WRITE RECORDS IN A FILE AND THEN READ IT RECORDS IN SORTED ORDER BY NAMES IN RECORD
//AND DISPLAY THEM ON SCREEN
#include
#include
#include
int main()
{
FILE *fw,*fr;
char opsn=’y’;
char *p;
int count=0;
//for writing records into file
struct student
{
char name[20];
int age;
}s;
fw=fopen(“op.txt”,”w”);
while(opsn==’y’)
{
count++;
printf(“Enter student name and age\n”);
scanf(“%s%d”,s.name,&s.age);
fprintf(fw,”%3s%3d\n”,s.name,s.age);
printf(“Wanna enter another record(y|n)\n”);
fflush(stdin);
opsn=getche();
}
fclose(fw);
//for reading records rom file
fr=fopen(“op.txt”,”r”);
struct st
{
char nm[20];
int ag;
}s2[count];
printf(“\nRecord from file is\n”);
int i=0,j;
char temp[20];
while(fscanf(fr,”%s%d”,s.name,&s.age)!=EOF)
{
strcpy(s2[i].nm,s.name);
s2[i].ag=s.age;
i++;
}
// for sorting records
for(i=0;i<count;i++)
{ for(j=i+1;j0)
{
strcpy(temp,s2[i].nm);
strcpy(s2[i].nm,s2[j].nm);
strcpy(s2[j].nm,temp);
}}}
//for displaying records
for(i=0;i<count;i++)
printf("\n%s\t\t%d",s2[i].nm,s2[i].ag);
fclose(fr);
}
hi i have a question regarding c program.
how can i do this?
write a program that reads a file (file1) containing random strings. my program must be able to create another file (file2), to copy the contents of file1. my program should be able to alphabetically sort the contents of file2. my probplem is i dont know to sort the existing file. hope i can get some answer thank you.
@joanna: you should try to sort file strings as normal strings.
sorting method is same for both but accessing method for strings is different.
try to understand in parts.
write aprogram of updation in file
I want you to show me the codes to display the bellow output (form of rectangle using stars in c file):
how to design structure by using three dimentional vector?
I come from a background in the Pick OS where we do a READ and get the whole item which is delineated by attribute marks char(254), value marks char(253) and sub-value marks char(252). What I am wondering how would a Pick READ, implemented in C I assume, would that be done?
I found that Pick is the only OS/DataBase management system to be capable of a READ of the nature I describe.
Just curious.
How can I end a file , while getting characters as input and wanna to save them?
Marshall,
I have no idea how the Pick system is implemented. I worked at Pick Systems for years as a tech support person. I often worked with the programmers but never actually asked how the system was implemented. I would assume, and you know what that means, that it was written in C, C++ or … At Microdata, one of the Licensee’s of Pick, wrote it in Pick Assembly. Since Pick Systems, now Tiger Data I think, was porting to other platforms, AIX, PC, and hosting on Linux, C++ or C would see to be the likely candidates.
If I am wrong, please correct me.
tell me what is use of file handling concepts compare with structures
can u send me a c programe for updating the employee address with the help of file handling.
hey im very bad in programng..could u plz help me….thankk uu….
Thanks for the tutorial. Now I have a doubt that how to write to file in specific path?
how can append a file to main file if filename is used in main file?
how to over write a details using file handling
thank you for your tutorial….
thanks for ur codding
good explanation…..
what is use of file handling concepts ?
C language is very easy language.
http://www.gnu.org/software/libc/manual/html_mono/libc.html#Block-Input_002fOutput
this does not works dude
I want to increment the content of one file by one whenever that file opens,
I.e;just take an example as account number.whenever we are creating a new account program should return the account no, and also it should increment every accessing time
Hi
Thanks
It’s exactly what i need. and It works well
Thanks again 😉
if there is a text file that already has data in it……can we reach to any part using fseek and just EDIT the file??
if yes, how do we reach the point where we want to reach?
vijay thank a lot man, but can you please explain the logarithmic logic of it? please dude
how can I update a or change a flight itinerary destination and origin using the flight id without destroying the other descriptions?
please make it clear to me is it necessary in file processing is it necessary to through light on fgetch (), fgets(), fread (), fputc ()
please make it clear to me
in file processing is it necessary to through light on fgetch (), fgets(), fread (), fputc ()
please tell me ?
what is file handling?
When to use fgets,fputs, over fread,fwrite, I’m confused with these.
very help to us to do complex programs
how can i add, view, and delete using file handling? or in turbo ?
plz tell mi..can we declare file handling as global file..
What is recursion?
File processing in C?
Really very thanks! As always …. helping me making my project.
File handling concept