开发者

fwrite => fprintf

I'm having trouble changing the line fwrite(tmp_array, sizeof(int), num, f); to fpri开发者_StackOverflow社区ntf.

Can someone please take a look for me?

 void generate_random_sorted_file(const char *file_name, int num)
 {
     FILE *f = fopen(file_name, "wb");
     if (f==NULL) 
     {
         printf("could not open %s\n", file_name);
         return;
     }

     int *tmp_array = calloc(num, sizeof(int));
     int i;

     for (i=0; i<num; i++)
     tmp_array[i]=rand();

     qsort (tmp_array, num, sizeof(int), compare); /* sorts the array */
     fwrite(tmp_array, sizeof(int), num, f);

     fclose(f);
 }


fprintf will write the your integer array as text, if that's what you want, do something like

int i;
for(i = 0; i < num; i++)
  fprintf(f,"%d ",tmp_array[i]);


for (i=0; i<num; i++)
    fprintf(f, "%d ", tmp_array[i]);

If you want to format it differently you can do, but this is the bare bones. For example, adding line breaks every 10 items:

for (i=0; i<num; i++)
{
    fprintf(f, "%d ", tmp_array[i]);
    if ((i+1) % 10 == 0)
        fprintf(f, "\n");
}

Or perhaps you want tab separators:

fprintf(f, "%d\t", tmp_array[i]);


You will have to replace fwrite(...) with

for(i=0; i < num; i++)  
fprintf( f, "%d", tmp_array[i] );  

But why would you want to do that?


Are you trying to write a text file rather than a binary file? You're going to need to use a loop, something like this:

for (int i=0; i<num; ++i)
    fprintf(f, "%d\n", tmp_array[i]);


The following for loop should solve your problem by traversing tmp_array and printing each value to f. Try using,

for (int i=0; i < num; i++) {
    fprintf(f, "%d\n", tmp_array[i]);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜