简体   繁体   中英

fwrite => fprintf

I'm having trouble changing the line fwrite(tmp_array, sizeof(int), num, f); to fprintf .

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]);

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]);
}
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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM