Advertisement
DrAungWinHtut

fileio2.c

Nov 17th, 2022
663
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.10 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h> //exit()
  3.  
  4. int main()
  5. {
  6.     FILE* fo;
  7.     FILE* fi;
  8.     FILE* fo2;
  9.  
  10.     float A[10];
  11.     float L[10] = { 1.7,2.3,4.6,7.8,1,2,3,4,5,6};
  12.     float W[10] = { 5.2,4.1,1.6,6.8,7,8,9,0,9,8 };
  13.  
  14.     fopen_s(&fo, "I:\\test\\area.dat", "w"); //a - append
  15.  
  16.     if (fo == NULL)
  17.     {
  18.         printf("!Error, cannot open file!");
  19.         exit(1);
  20.     }
  21.  
  22.     for (int i = 0; i < 10; i++)
  23.     {
  24.         A[i] = L[i] * W[i];
  25.         printf("%d L=%0.2f W=%0.2f A=%0.2f\n",i+1, L[i], W[i], A[i]);
  26.         fprintf_s(fo, "%0.2f\n",A[i]);
  27.     }  
  28.    
  29.     fclose(fo);
  30.  
  31.     fopen_s(&fi, "I:\\test\\area.dat", "r"); //r - read
  32.  
  33.     if (fi == NULL)
  34.     {
  35.         printf("!Error, cannot open file!");
  36.         exit(1);
  37.     }
  38.  
  39.     float A2[20] = {};
  40.     for (int u = 0; u < 20; u++)
  41.     {
  42.         A2[u] = -1;
  43.     }
  44.  
  45.  
  46.     float data = 0.0;
  47.     int fstatus = 0;
  48.     int index = 0;
  49.  
  50.     do {
  51.         fstatus = fscanf_s(fi, "%f", &data); //success = 1 , fail = -1
  52.         if (fstatus == 1)//OK
  53.         {
  54.             A2[index] = data;
  55.             index++;
  56.         }
  57.        
  58.     } while (fstatus != -1);
  59.     fclose(fi);
  60.  
  61.     int h = 0;
  62.  
  63.     while(A2[h]!=-1)
  64.     {
  65.         printf("Read data from file is %f\n", A2[h]);
  66.         h++;
  67.     }
  68.    
  69.  
  70.  
  71.    
  72.     return 0;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement