我有一个二维矩阵:
char clientdata[12][128];
如何最好地将内容写入文件?我需要不断更新此文本文件,因此在每次写操作时都会清除文件中的先前数据。
我有一个二维矩阵:
char clientdata[12][128];
如何最好地将内容写入文件?我需要不断更新此文本文件,因此在每次写操作时都会清除文件中的先前数据。
由于数据大小固定,将整个数组写入文件的一种简单方法是使用二进制写入模式:
FILE *f = fopen("client.data", "wb");
fwrite(clientdata, sizeof(char), sizeof(clientdata), f);
fclose(f);
这将一次性写出整个2D数组,覆盖之前存在的文件内容。
FILE *ifp = fopen("client.data", "rb"); fread(clientdata, sizeof(char), sizeof(clientdata), ifp);
并添加错误检查。 使用以下翻译以添加错误检查:FILE *ifp = fopen("client.data", "rb");
if (ifp == NULL) {
// 处理打开文件失败的情况
}
if(fread(clientdata, sizeof(char), sizeof(clientdata), ifp) != sizeof(clientdata)){
// 处理读取文件失败的情况
}
- Jonathan Lefflerint 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);
/* 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/]