File I/O

I have a file to write in binary mode. Right now I am doing this as below


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int main()
{
   int num;
   long long time;
   FILE *fin = fopen("test1.txt", "r");
   FILE *fout = fopen("test2.out", "wb");

   while(!feof(fin))
   {
      fscanf(fin, "%d %lld", &num, &time);
      fwrite(&num, sizeof(num), 1, fout);
      fwrite(&time, sizeof(time), 1, fout);
   }
   
   fclose(fin);
   fclose(fout);
   return 0;
}


I want to reduce the number of fwrite calls. Lets say by buffering the inputs. How to do that?
FILE* i/o is buffered.
rachitagrawal wrote:
I want to reduce the number of fwrite calls.

Why?
@kbw But I guess they are fixed for all architecture and all OS that might not be optimal. Isn't it?

@PanGalactic: I want to reduce the overhead due to repeatitive I/O.
fixed for all architecture

What?

You can change the buffer size with setbuf.
@kbw: Buffer length.

Oh ok. I didnt have idea about the setbuf.

One more thing, I was trying to buffer it with a structure. But somehow, its not working. Just curious to know what is the problem. See if you can figure it out?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
struct buffer_t
{
   int num;
   long long time;
};

int main()
{
   int num;
   long long time;
   struct buffer_t bWrite[16];
   FILE *fin = fopen("test1.txt", "r");
   FILE *fout = fopen("test2.out", "wb");

   while(!feof(fin))
   {
      fscanf(fin, "%d %lld", &num, &time);
     
      if(i  == 16)
      {
          fwrite(&bWrite, sizeof(bWrite), 16, fout);
          i == 0;
      }

      bWrite[i].num = num;
      bWrite[i].time = time;
      i++;
   }
   
   fwrite(&bWrite, sizeof(bWrite), i, fout);
   fclose(fin);
   fclose(fout)
   return 0;
}
Have you checked the size of int, long long and buffer_t? You'll probably find that buffer_t is larger than the sum of it's parts. You need to pack the structure to byte alignment.
Oh ok, I got the problem. Thank you. :)
Topic archived. No new replies allowed.