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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18597685/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:21:27  来源:igfitidea点击:

How to write an array to file in C

cio

提问by mugetsu

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 this text file so on every write the previous data in the file is cleared.

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

回答by dasblinkenlight

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.

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

回答by Mohamed ROMDANE

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

我宁愿添加一个测试以使其健壮!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);

回答by user3359049

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

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

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

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