Advertisement
DrAungWinHtut

FileIO2.c

Nov 23rd, 2022 (edited)
808
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.50 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h> //exit()
  3.  
  4. int main()
  5. {
  6.     FILE* fpl;
  7.     FILE* fpw;
  8.     FILE* fpa;
  9.  
  10.     float l[20] ;
  11.     float w[20];
  12.     float a[20];
  13.  
  14.     int fstatus = 0; // 0 - neutral
  15.     float data = 0.0;
  16.     int index = 0;
  17.     int lcount = 0;
  18.     int wcount = 0;
  19.  
  20.     for (int k = 0; k < 20; k++)
  21.     {
  22.         l[k] = -1;
  23.         w[k] = -1;
  24.         a[k] = -1;
  25.     }
  26.  
  27.  
  28.     //1-read l values and store in l array
  29.     fopen_s(&fpl, "I:\\test\\l.txt", "r");
  30.     if (fpl == NULL)
  31.     {
  32.         printf("!Error, cannot open file!");
  33.         exit(1);
  34.     }
  35.     do {
  36.         fstatus = fscanf_s(fpl, "%f", &data); //success = 1 , fail = -1
  37.         if (fstatus == 1)//1 - OK | -1 Not OK
  38.         {
  39.             l[index] = data;
  40.             index++;
  41.         }
  42.     } while (fstatus != -1);
  43.     lcount = index;
  44.     fclose(fpl);
  45.  
  46.     //2-read w values and store in w array
  47.     index = 0;
  48.     fopen_s(&fpw, "I:\\test\\w.txt", "r");
  49.     if (fpw == NULL)
  50.     {
  51.         printf("!Error, cannot open file!");
  52.         exit(1);
  53.     }
  54.     do {
  55.         fstatus = fscanf_s(fpw, "%f", &data); //success = 1 , fail = -1
  56.         if (fstatus == 1)//1 - OK | -1 Not OK
  57.         {
  58.             w[index] = data;
  59.             index++;
  60.         }
  61.     } while (fstatus != -1);
  62.     wcount = index;
  63.     fclose(fpw);
  64.  
  65.     //3-calculate area and store in a.txt file
  66.     if (lcount == wcount)
  67.     {
  68.         for (int j = 0; j < lcount; j++)
  69.         {
  70.             a[j] = l[j] * w[j];
  71.         }
  72.     }
  73.     fopen_s(&fpa, "I:\\test\\a.txt", "w");
  74.     if (fpa == NULL)
  75.     {
  76.         printf("!Error, cannot open file!");
  77.         exit(1);
  78.     }
  79.     for (int z = 0; z < lcount; z++)
  80.     {
  81.         fprintf_s(fpa, "%0.2f\n", a[z]);
  82.     }
  83.     fclose(fpa); //really save to file in harddisk
  84.     return 0;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement