Advertisement
Guest User

file handling

a guest
Nov 30th, 2015
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.34 KB | None | 0 0
  1.  
  2. File Handling in C with Examples (fopen, fread, fwrite, fseek)
  3.  
  4. by Himanshu Arora on July 9, 2012
  5.  
  6.  
  7.  
  8.  
  9.  
  10.  
  11.  
  12. 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.
  13.  
  14.  
  15. 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.
  16.  
  17. File handling functions
  18.  
  19. In this article, we will cover the following functions that are popularly used in file handling :
  20.  
  21. fopen()
  22. FILE *fopen(const char *path, const char *mode);
  23.  
  24.  
  25. 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 :
  26. ◾‘r’ : Open text file for reading. The stream is positioned at the beginning of the file.
  27. ◾‘r+’ : Open for reading and writing. The stream is positioned at the beginning of the file.
  28. ◾‘w’ : Truncate file to zero length or create text file for writing. The stream is positioned at the beginning of the file.
  29. ◾‘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.
  30. ◾‘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.
  31. ◾‘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.
  32.  
  33. The fopen() function returns a FILE stream pointer on success while it returns NULL in case of a failure.
  34.  
  35. fread() and fwrite()
  36. size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
  37.  
  38. size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
  39.  
  40.  
  41. 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.
  42.  
  43. 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.
  44.  
  45.  
  46.  
  47.  
  48. fseek()
  49. int fseek(FILE *stream, long offset, int whence);
  50.  
  51.  
  52. 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.
  53.  
  54. Upon success, this function returns 0, otherwise it returns -1.
  55.  
  56. fclose()
  57. int fclose(FILE *fp);
  58.  
  59.  
  60. 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.
  61.  
  62. The code
  63. #include<stdio.h>
  64. #include<string.h>
  65.  
  66. #define SIZE 1
  67. #define NUMELEM 5
  68.  
  69. int main(void)
  70. {
  71. FILE* fd = NULL;
  72. char buff[100];
  73. memset(buff,0,sizeof(buff));
  74.  
  75. fd = fopen("test.txt","rw+");
  76.  
  77. if(NULL == fd)
  78. {
  79. printf("\n fopen() Error!!!\n");
  80. return 1;
  81. }
  82.  
  83. printf("\n File opened successfully through fopen()\n");
  84.  
  85. if(SIZE*NUMELEM != fread(buff,SIZE,NUMELEM,fd))
  86. {
  87. printf("\n fread() failed\n");
  88. return 1;
  89. }
  90.  
  91. printf("\n Some bytes successfully read through fread()\n");
  92.  
  93. printf("\n The bytes read are [%s]\n",buff);
  94.  
  95. if(0 != fseek(fd,11,SEEK_CUR))
  96. {
  97. printf("\n fseek() failed\n");
  98. return 1;
  99. }
  100.  
  101. printf("\n fseek() successful\n");
  102.  
  103. if(SIZE*NUMELEM != fwrite(buff,SIZE,strlen(buff),fd))
  104. {
  105. printf("\n fwrite() failed\n");
  106. return 1;
  107. }
  108.  
  109. printf("\n fwrite() successful, data written to text file\n");
  110.  
  111. fclose(fd);
  112.  
  113. printf("\n File stream closed through fclose()\n");
  114.  
  115. return 0;
  116. }
  117.  
  118. The code above assumes that you have a test file “test.txt” placed in the same location from where this executable will be run.
  119.  
  120. Initially the content in file is :
  121. $ cat test.txt
  122. hello everybody
  123.  
  124. Now, run the code :
  125. $ ./fileHandling
  126.  
  127. File opened successfully through fopen()
  128.  
  129. Some bytes successfully read through fread()
  130.  
  131. The bytes read are [hello]
  132.  
  133. fseek() successful
  134.  
  135. fwrite() successful, data written to text file
  136.  
  137. File stream closed through fclose()
  138.  
  139. Again check the contents of the file test.txt. As you see below, the content of the file was modified
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement