How to write an array to file in C

前端 未结 3 1929
悲哀的现实
悲哀的现实 2020-12-09 05:07

I have a 2 dimensional matrix:

char clientdata[12][128];

What is the best way to write the contents to a file? I need to constantly update

相关标签:
3条回答
  • 2020-12-09 05:36

    Since the size of the data is fixed, one simple way of writing this entire array into a file is using the binary writing mode:

    FILE *f = fopen("client.data", "wb");
    fwrite(clientdata, sizeof(char), sizeof(clientdata), f);
    fclose(f);
    

    This writes out the whole 2D array at once, writing over the content of the file that has been there previously.

    0 讨论(0)
  • 2020-12-09 05:37

    I would rather add a test to make it robust ! The fclose() is done in either cases otherwise the file system will free the file descriptor

    int written = 0;
    FILE *f = fopen("client.data", "wb");
    written = fwrite(clientdata, sizeof(char), sizeof(clientdata), f);
    if (written == 0) {
        printf("Error during writing to file !");
    }
    fclose(f);
    
    0 讨论(0)
  • 2020-12-09 05:49

    How incredibly simple this issue turned out to be... The example given above handle characters, this is how to handle an array of integers...

    /* define array, counter, and file name, and open the file */
    int unsigned n, prime[1000000];
    FILE *fp;
    fp=fopen("/Users/Robert/Prime/Data100","w");
    prime[0] = 1;  /* fist prime is One, a given, so set it */
    /* do Prime calculation here and store each new prime found in the array */
    prime[pn] = n; 
    /* when search for primes is complete write the entire array to file */
    fwrite(prime,sizeof(prime),1,fp); /* Write to File */
    
    /* To verify data has been properly written to file... */
    fread(prime,sizeof(prime),1,fp); /* read the entire file into the array */
    printf("Prime extracted from file Data100: %10d \n",prime[78485]); /* verify data written */
    /* in this example, the 78,485th prime found, value 999,773. */
    

    For anyone else looking for guidance on C programming, this site is excellent...

    Refer: [https://overiq.com/c-programming/101/fwrite-function-in-c/

    0 讨论(0)
提交回复
热议问题