18

我有一个二维矩阵:

char clientdata[12][128];

将内容写入文件的最佳方法是什么?我需要不断更新这个文本文件,以便每次写入文件中的先前数据都会被清除。

4

3 回答 3

36

由于数据的大小是固定的,将整个数组写入文件的一种简单方法是使用二进制写入模式:

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

这会立即写出整个 2D 数组,覆盖之前存在的文件内容。

于 2013-09-03T17:04:18.710 回答
1

我宁愿添加一个测试以使其健壮!fclose() 在任何一种情况下都会完成,否则文件系统将释放文件描述符

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);
于 2017-12-01T17:58:00.483 回答
1

这个问题原来是多么的简单......上面给出的例子处理字符,这是如何处理整数数组......

/* 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. */

对于其他寻求 C 编程指导的人来说,这个网站非常棒......

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

于 2018-09-17T01:57:02.920 回答