文件问题
各位大佬帮帮我i这个小菜鸡就是将将数组a的值写进文件,然后在从文件中读出来保存到数组b(保存到数组b不会)
恳求各位大佬指点一下
#include <stdio.h>
#define N 5
void main()
{
int a, b;
int i, size = sizeof(int);
FILE*fp;
if((fp = fopen("a","wb"))==NULL)
{
puts("Fall to open file");
exit(0);
}
for(i = 0; i < N; i++)//循环赋值
{
scanf("%d",&a);
}
fwrite(a, size, N, fp);//数组a写入文件
rewind(fp);
fread(a, size, N, fp);//将数据读出并保存到数组b中,这一步不知道怎么写了
for(i = 0; i < N; i++)
{
printf(" %d ",b);
}
printf("\n");
fclose(fp);
})
#include <stdio.h>
void file_write(const char *filename, const void *data, size_t size) {
FILE *fp = fopen(filename, "wb");
if(!fp) return;
fwrite(data, 1, size, fp);
fclose(fp);
}
void file_read(const char *filename, void *data, size_t size) {
FILE *fp = fopen(filename, "rb");
if(!fp) return;
fread(data, 1, size, fp);
fclose(fp);
}
int main(void) {
const int N = 5;
int a, b;
for(size_t i = 0; i < N; ++i) scanf("%d", &a);
file_write("a", a, sizeof(a) * N);
file_read("a", b, sizeof(b) * N);
for(size_t i = 0; i < N; ++i) printf("%d ", b);
puts("");
return 0;
}
#include <stdio.h>
#define N 5
void main()
{
int a, b;
int i, size = sizeof(int);
FILE*fp;
if((fp = fopen("a","wb"))==NULL)
{
puts("Fail to open file");//英语语法错误,FALL和FAIL的意思不一样,这里应该用fail
exit(0);
}
for(i = 0; i < N; i++)//循环赋值
{
scanf("%d",&a);
}
fwrite(a, size, N, fp);//数组a写入文件
rewind(fp);
fread(b, size, N, fp);//直接将文件里的东西放到B所指空间
for(i = 0; i < N; i++)
{
printf(" %d ",b);
}
printf("\n");
fclose(fp);
}
页:
[1]