关于c语言文件操作

来源:百度知道 编辑:UC知道 时间:2024/07/02 14:22:09
实现功能:把a[2][2]={1,2,3,4,}分行写入c:\a.txt中,然后再从文件中读取出来。
谢谢!
数组在a.txt中的存储为:
1,2
3,4

#include <stdio.h>
main()
{
int a[2][2] = {1,2,3,4};
FILE *fp_in, *fp_out;
char buf[20];
int i, j;

fp_out = fopen("c:\a.txt", "w");
for(i = 0; i < 2; i++){
for(j = 0; j < 2; j++){
fprintf(fp_out, "%d ", a[i][j]);
}
}
fclose(fp_out);

fp_in = fopen("c:\a.txt", "r");
if(fp_in == NULL){
printf("error");
return(0);
}
else{
fgets(buf, 20, fp_in);
printf("%s", buf);
fclose(fp_in);
}
return(0);
}
已测试成功!

FILE* fp = fopen("a.txt","wb");
if ( !fp )
return;
char text[255];
sprintf(text, "%d,%d\r\n%d,%d\r\n", a[0][0],a[0][1], a[1][0], a[1][1] );
fwrite( text, strlen(text), 1, fp );

//读出
char buf[255];
fread( buf, sizeof(buf), 1, fp ); // 或者用fgets<