如何在C语言中将数组写入文件

21

我有一个二维矩阵:

char clientdata[12][128];

如何最好地将内容写入文件?我需要不断更新此文本文件,因此在每次写操作时都会清除文件中的先前数据。


3
这个文件应该是可读的人类文本文件吗? - Sergey Kalinichenko
数据是数字吗?字符串?这里发生了什么?你能展示一下数据的例子以及你想要文件看起来像什么吗? - Carl Norum
将2D数组写入C文件的副本: - sara
"4", "error_msg", "21.1"。需要这个文件,以便在需要时再次提取数据。因此,在文本文件中它不必是人类可读的,只有在再次提取时才需要。 - mugetsu
3个回答

41

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

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

这将一次性写出整个2D数组,覆盖之前存在的文件内容。


4
使用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 Leffler
5
这个方法适用于不同类型的计算机,因为数据是字符数据。如果数据是整型,那么它将不能在大端和小端字节序不同的计算机之间传输。 - Jonathan Leffler
我很惊讶自己找到一个好的、简洁的答案是多么困难。谢谢!谢谢,谢谢!<3 - Sipty

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

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/]


3
我知道这不是世界上最重要的评论,但1 不是质数。 - RGS
按照定义,质数是一个大于1的自然数,不能通过两个较小的自然数相乘得到。我刚刚意识到需要在我的数组中包含1作为第一个元素,因为它对所有质数都至关重要。 - user3359049

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接