dmilicev

lets_learn_c_files_with_array_of_int_v1.c

Nov 4th, 2019
208
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 12.37 KB | None
  1. /*
  2.  
  3.     lets_learn_c_files_with_array_of_int_v1.c
  4.  
  5. Work in C with text and binary files.
  6.  
  7. The idea is that this program should cover everything about
  8. text and binary files in C.
  9.  
  10.  C work with files:
  11.  
  12. Write an array of integers into a text (txt) file.
  13.  
  14. Read array of integers from text (txt) file.
  15.  
  16.  
  17. Write an array of integers into a binary (bin) file.
  18.  
  19. Read an array of integers from binary (bin) file.
  20.  
  21.  
  22. The program has many comments because it is intended for beginners.
  23.  
  24. I want to encourage beginners in programming to study this program
  25. regardless of the fact that it consists of many lines.
  26. Half of these lines belong to the comments and explanations.
  27.  
  28. The point of the functions is to divide a big problem
  29. into several smaller problems.
  30. Each function should solve only one problem and nothing more.
  31. Functions should therefore not have more than a couple dozen lines of code.
  32. The features of the functions are arguments (parameters, input values)
  33. and the value returned by the function to the part of the program
  34. from which it was called.
  35. If we pass to the function the pointers to the variables as arguments,
  36. function then has the ability to change the value of the arguments
  37. beyond its scope, and in that case it does not even have to have
  38. its own return value.
  39. Our conversations should soon come down to questions about how to write
  40. a function that receives those arguments and has that return value.
  41.  
  42. Please understand that English is not my native language and
  43. please feel free to correct me about it.
  44.  
  45. Feel free to let me know if you think I left out something,
  46. or if you find some bugs in this program.
  47.  
  48. This program will be updated according to your suggestions.
  49.  
  50. Author Dragan Milicev
  51. https://www.facebook.com/dmilicev
  52. You can find all my C programs at Dragan Milicev's pastebin:
  53. https://pastebin.com/u/dmilicev
  54.  
  55.  
  56. ----------Work with text and binary files in C-------------------------------
  57.  
  58.  
  59. https://www.tutorialspoint.com/cprogramming/c_file_io.htm
  60.  
  61. https://www.tutorialspoint.com/ansi_c/c_working_with_files.htm
  62.  
  63.  
  64. ----------Writing a text file------------------------------------------------
  65.  
  66. int fputc(int char, FILE *stream)
  67.  
  68. Writes a character (an unsigned char) specified by the argument char
  69. to the specified stream and advances the position indicator for the stream.
  70.  
  71. https://www.tutorialspoint.com/c_standard_library/c_function_fputc.htm
  72.  
  73.     FILE *fp;
  74.     int ch;
  75.  
  76.     fputc(ch, fp);
  77.  
  78. -----------------------------
  79.  
  80. int fputs( const char *s, FILE *fp );
  81.  
  82. Writes the string s to the output stream referenced by fp,
  83. but not including the null character.
  84. It returns a non-negative value on success,
  85. otherwise EOF is returned in case of any error.
  86.  
  87. https://www.tutorialspoint.com/c_standard_library/c_function_fputs.htm
  88.  
  89.     fputs("This is testing for fputs...\n", fp);
  90.  
  91. -----------------------------
  92.  
  93. You can use
  94.  
  95. int fprintf(FILE *fp,const char *format, ...)
  96.  
  97. function as well to write a string into a file.
  98. Sends formatted output to a stream.
  99.  
  100. https://www.tutorialspoint.com/c_standard_library/c_function_fprintf.htm
  101.  
  102.     fprintf(fp, "%s %s %s %d", "We", "are", "in", 2019);
  103.  
  104.  
  105. ----------Reading a text file------------------------------------------------
  106.  
  107. int fgetc(FILE *stream)
  108.  
  109. gets the next character (an unsigned char) from the specified stream
  110. and advances the position indicator for the stream.
  111.  
  112. https://www.tutorialspoint.com/c_standard_library/c_function_fgetc.htm
  113.  
  114.     int c;
  115.  
  116.     c = fgetc(fp);
  117.  
  118. -----------------------------
  119.  
  120. char *fgets(char *str, int n, FILE *stream)
  121.  
  122. reads a line from the specified stream
  123. and stores it into the string pointed to by str.
  124. It stops when either (n-1) characters are read,
  125. the newline character is read,
  126. or the end-of-file is reached, whichever comes first.
  127.  
  128. https://www.tutorialspoint.com/c_standard_library/c_function_fgets.htm
  129.  
  130.     char str[60];
  131.  
  132.     fgets (str, 60, fp);
  133.  
  134. -----------------------------
  135.  
  136. You can also use
  137.  
  138. int fscanf(FILE *fp, const char *format, ...)
  139.  
  140. function to read strings from a file,
  141. but it stops reading after encountering the first space character.
  142. Reads formatted input from a stream.
  143.  
  144. https://www.tutorialspoint.com/c_standard_library/c_function_fscanf.htm
  145.  
  146.     char str1[10], str2[10], str3[10];
  147.     int year;
  148.  
  149.     fscanf(fp, "%s %s %s %d", str1, str2, str3, &year);
  150.  
  151.  
  152.  
  153. ----------Closing a text or binary file--------------------------------------
  154.  
  155. int fclose(FILE *stream)
  156. Closes the stream. All buffers are flushed.
  157.  
  158. https://www.tutorialspoint.com/c_standard_library/c_function_fclose.htm
  159.  
  160. FILE *fp;
  161.  
  162. fclose(fp);
  163.  
  164.  
  165. ----------Writing a binary file----------------------------------------------
  166.  
  167.  
  168. size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  169.  
  170. or more clearly:
  171.  
  172. size_t fwrite(const void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);
  173.  
  174. Writes data from the array pointed to, by ptr to the given stream.
  175.  
  176. https://www.tutorialspoint.com/c_standard_library/c_function_fwrite.htm
  177.  
  178.     FILE *fp;
  179.     char str[] = "This is tutorialspoint.com";
  180.  
  181.     fwrite(str , 1 , sizeof(str) , fp );
  182.     fflush( fp );
  183.  
  184. -----------------------------
  185.  
  186. int fflush(FILE *stream)
  187. flushes the output buffer of a stream.
  188.  
  189. https://www.tutorialspoint.com/c_standard_library/c_function_fflush.htm
  190.  
  191.  
  192.  
  193. ----------Reading a binary file----------------------------------------------
  194.  
  195. size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
  196.  
  197. or more clearly:
  198.  
  199. size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);
  200.  
  201. reads data from the given stream into the array pointed to, by ptr.
  202.  
  203. https://www.tutorialspoint.com/c_standard_library/c_function_fread.htm
  204.  
  205.     FILE *fp;
  206.     char c[] = "this is tutorialspoint";
  207.     char buffer[100];
  208.  
  209.     fread(buffer, strlen(c)+1, 1, fp);
  210.  
  211.  
  212.  
  213. ----------Walk through text or binary file-----------------------------------
  214.  
  215.  
  216. long int ftell(FILE *stream)
  217.  
  218. Returns the current file position of the given stream.
  219. Returns the current value of the position indicator.
  220. If an error occurs, -1L is returned,
  221. and the global variable errno is set to a positive value.
  222.  
  223. https://www.tutorialspoint.com/c_standard_library/c_function_ftell.htm
  224.  
  225.     FILE *fp;
  226.     int len;    // or   long int len;
  227.  
  228.     len = ftell(fp);
  229.  
  230. -----------------------------------------------------------------------------
  231.  
  232. int fseek(FILE *stream, long int offset, int whence)
  233.  
  234. sets the file position of the stream to the given offset.
  235.  
  236. https://www.tutorialspoint.com/c_standard_library/c_function_fseek.htm
  237.  
  238. offset is the number of bytes to offset from whence.
  239.  
  240. whence is the position from where offset is added.
  241. It is specified by one of the following constants:
  242.  
  243. 0 SEEK_SET  Beginning of file
  244. 1 SEEK_CUR  Current position of the file pointer
  245. 2 SEEK_END  End of file
  246.  
  247.     FILE *fp;
  248.  
  249.     fseek( fp, 7, SEEK_SET );
  250.  
  251.  
  252. -----------------------------------------------------------------------------
  253.  
  254. void rewind(FILE *stream)
  255.  
  256. sets the file position to the beginning of the file of the given stream.
  257.  
  258. https://www.tutorialspoint.com/c_standard_library/c_function_rewind.htm
  259.  
  260.     FILE *fp;
  261.  
  262.     rewind(fp);
  263.  
  264.  
  265. -----------------------------------------------------------------------------
  266.  
  267. */
  268.  
  269.  
  270. #include <stdio.h>
  271. #include<stdlib.h>          // for exit()
  272.  
  273.  
  274. // print array arr[] of n integers
  275. void print_array( char text[], int arr[], int n )
  276. {
  277.     int i;
  278.  
  279.     printf("\n\n%s", text );
  280.     for( i=0; i<n; i++ ) {
  281.         printf(" %d", arr[i] );
  282.     }
  283.     printf("\n");
  284. }
  285.  
  286.  
  287. void write_to_text_file_array_of_integers( char FileName[], int arr[], int n )
  288. {
  289.     FILE *p_file;
  290.     int i;
  291.  
  292.     p_file = fopen(FileName, "w");
  293.  
  294.     if( p_file == NULL ) {
  295.         printf("\n Error opening output text file ! \n");
  296.         exit(1);
  297.     }
  298.  
  299.     printf("\n");
  300.  
  301.     // we write one by one integer from array in a text file
  302.     for( i=0; i<n; i++ ) {
  303.         printf("\n Writing to a text file %s  arr[%d] = %d ", FileName, i, arr[i] );
  304.         fprintf( p_file, "%d ", arr[i] );
  305.     }
  306.  
  307.     fclose(p_file);
  308. }
  309.  
  310.  
  311. void read_from_text_file_array_of_integers( char FileName[], int arr[], int n )
  312. {
  313.     FILE *p_file;
  314.     int i;
  315.  
  316.     p_file = fopen(FileName, "r");
  317.  
  318.     if( p_file == NULL ) {
  319.         printf("\n Error opening input text file ! \n");
  320.         exit(1);
  321.     }
  322.  
  323.     printf("\n");
  324.  
  325.     // we read one by one integer from text file to array of integers arr[]
  326.     for( i=0; i<n; i++ ) {
  327.         fscanf( p_file, "%d ", &arr[i] );   // it must be the same format as when writing
  328.         printf("\n Read from text file %s  arr[%d] = %d", FileName, i, arr[i] );
  329.     }
  330.  
  331.     fclose(p_file);
  332. }
  333.  
  334.  
  335. void write_to_binary_file_array_of_integers( char FileName[], int arr[], int n )
  336. {
  337.     FILE *p_file;
  338.     int i=0;        // = 0 is required !!!
  339.  
  340.     p_file = fopen(FileName, "wb");
  341.  
  342.     if( p_file == NULL ) {
  343.         printf("\n Error opening input binary file ! \n");
  344.         exit(1);
  345.     }
  346.  
  347. /*
  348.     // we write one by one integers from array arr[] to the binary file
  349.     for( i=0; i<n; i++ ) {
  350.         printf("\n Writing to a binary file arr[%d] = %d", i,arr[i] );
  351.         fwrite( &arr[i], sizeof(arr[i]), 1, p_file );
  352.     }
  353. */
  354.  
  355.     // at once we write the whole arr[] of n integers into the binary file
  356.     fwrite( &arr[i], sizeof(arr[i]), n, p_file );
  357.     fflush(p_file); // when writing to file, it is obligatory fflush !!!
  358.  
  359.     fclose(p_file);
  360. }
  361.  
  362.  
  363. void read_from_binary_file_array_of_integers( char FileName[], int arr[], int n )
  364. {
  365.     FILE *p_file;
  366.     int i=0;        // = 0 is required !!!
  367.  
  368.     p_file = fopen(FileName, "rb");
  369.  
  370.     if( p_file == NULL ) {
  371.         printf("\n Error opening input binary file ! \n");
  372.         exit(1);
  373.     }
  374.  
  375. /*
  376.  
  377. IMPORTANT !!!
  378.  
  379. The feof() function should not be called before attempting a read !
  380. The following code may cause an error :
  381.  
  382.     while (!feof(p_file))
  383.         fscanf( p_file, "%d", &number );
  384.  
  385. Code should be like this:
  386.  
  387. // We read the numbers from the file until we reach the end
  388. // and print them to standard output:
  389.  
  390.     while( 1 ) {                            // endless loop that breaks with break;
  391.  
  392.         int number;
  393.  
  394.         fscanf( p_file, "%d ", &number );   // We are trying to read the number
  395.  
  396.                                             // We print the number we readed
  397.         printf(" Readed from binary file : %d \n", number );
  398.  
  399.         if ( feof(p_file) )                 // If we reach the end of the file, we interrupt
  400.             break;
  401.     }
  402. */
  403.  
  404. /*
  405.     // or:
  406.     // we read one by one integer from binary file to array of integers arr[]
  407.     while( 1 ) {    // endless loop that breaks with break;
  408.  
  409.         fread( &arr[i], sizeof(arr[i]), 1, p_file );
  410.         printf("\n Read from binary file arr[%d] = %d ", i, arr[i] );
  411.         i++;
  412.  
  413.         if ( feof(fp) )             // If we reach the end of the file, we interrupt
  414.             break;
  415.     }
  416. */
  417.  
  418. /*
  419.     // or:
  420.     // we read one by one integer from binary file to array of integers arr[]
  421.     for( i=0; i<n; i++ ) {
  422.         fread( &arr[i], sizeof(int), 1, p_file );
  423.         printf("\n Read from binary file arr[%d] = %d ", i, arr[i] );
  424.     }
  425. */
  426.  
  427.     // we at once load all n integers in arr
  428.     fread( arr, sizeof(arr), n, p_file );
  429.  
  430.     fclose(p_file);
  431. }
  432.  
  433.  
  434.  
  435.  
  436. int main(void)
  437. {
  438.     int arr_1[100] = {1,2,3,4};  // array of integers
  439.     int arr_2[100] = {5,6,7,8};
  440.     int n1 = 4;                 // number of integers in array of integers
  441.     int n2 = 4;
  442.  
  443. // Text file:
  444.  
  445.     // write to text file array of integers
  446.     write_to_text_file_array_of_integers( "arr_1.txt", arr_1, n1 );
  447.     write_to_text_file_array_of_integers( "arr_2.txt", arr_2, n2 );
  448.  
  449.     // read from text file array of integers
  450.     read_from_text_file_array_of_integers("arr_1.txt",arr_1,n1);
  451.     read_from_text_file_array_of_integers("arr_2.txt",arr_2,n2);
  452.  
  453.     // print array
  454.     print_array( " arr_1 from text file is: ", arr_1, n1 );
  455.     print_array( " arr_2 from text file is: ", arr_2, n2 );
  456.  
  457.  
  458. // Binary file:
  459.  
  460.     // write to binary file array of integers
  461.     write_to_binary_file_array_of_integers( "arr_1.bin", arr_1, n1 );
  462.     write_to_binary_file_array_of_integers( "arr_2.bin", arr_2, n2 );
  463.  
  464.     // read from binary file array of integers
  465.     read_from_binary_file_array_of_integers( "arr_1.bin", arr_1, n1 );
  466.     read_from_binary_file_array_of_integers( "arr_2.bin", arr_2, n2 );
  467.  
  468.     // print array
  469.     print_array( " arr_1 from binary file is: ", arr_1, n1 );
  470.     print_array( " arr_2 from binary file is: ", arr_2, n2 );
  471.  
  472.  
  473.     printf("\n");
  474.     return 0;
  475. }
RAW Paste Data Copied