c从文件初始化数组使第一个元素-1
c initializing array from file makes first element -1
我在 ubuntu - 代码块。
我被困在一个更复杂的文件读取任务中,所以创建了最简单的测试,它向我抛出了这个奇怪的 "error"。
为了简单起见,我有 2 个全局变量
int a[20];
int row=20;
从文件初始化数组的函数
void load_file(char* filename) {
int i;
FILE* f;
f=fopen(filename, "r");
for (i=0; i<row; i++)
fscanf(f, "%d", &a[i]);
fclose(f);
}
另一个将数组保存到(同一个)文件的函数
void save_file(char* filename) {
int i;
FILE* f;
f=fopen(filename, "w");
for (i=0; i<row; i++)
fprintf(f, "%d", a[i]);
fclose(f);
}
因为我真的不知道这里可能有什么问题,所以程序中存在的其他两个函数:
void print_a() {
int i;
for (i=0; i<row; i++)
printf("%d ", a[i]);
printf("\n");
}
void init_a(int val) {
int i;
for (i=0; i<row; i++)
a[i]=val;
}
这是主要内容:
int main(){
init_a(2);
print_a();
init_a(5);
save_file("a.txt");
load_file("a.txt");
print_a();
return 0;
}
程序的输出是:
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
-1 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
所以"error"是加载文件后,数组第一个元素初始化为-1,而文件中只有20个5。
我真的不知道,谢谢你的帮助。
问题是您的 a.txt
看起来像这样:
55555555555555555555
所以当您再次尝试阅读它时,它确实而不是看起来像 20 个整数。它看起来像一个非常大的数字,对于整数来说太大了。
打印到文件时在每个整数之间添加一个space。像这样:
void save_file(char* filename) {
int i;
FILE* f;
f=fopen(filename, "w");
// Here you should check that f is valid before proceeding
for (i=0; i<row; i++)
fprintf(f, "%d ", a[i]);
// ^ notice
fclose(f);
}
此外,您应该始终检查 fopen
和 fscanf
中的 return 值
我在 ubuntu - 代码块。 我被困在一个更复杂的文件读取任务中,所以创建了最简单的测试,它向我抛出了这个奇怪的 "error"。
为了简单起见,我有 2 个全局变量
int a[20];
int row=20;
从文件初始化数组的函数
void load_file(char* filename) {
int i;
FILE* f;
f=fopen(filename, "r");
for (i=0; i<row; i++)
fscanf(f, "%d", &a[i]);
fclose(f);
}
另一个将数组保存到(同一个)文件的函数
void save_file(char* filename) {
int i;
FILE* f;
f=fopen(filename, "w");
for (i=0; i<row; i++)
fprintf(f, "%d", a[i]);
fclose(f);
}
因为我真的不知道这里可能有什么问题,所以程序中存在的其他两个函数:
void print_a() {
int i;
for (i=0; i<row; i++)
printf("%d ", a[i]);
printf("\n");
}
void init_a(int val) {
int i;
for (i=0; i<row; i++)
a[i]=val;
}
这是主要内容:
int main(){
init_a(2);
print_a();
init_a(5);
save_file("a.txt");
load_file("a.txt");
print_a();
return 0;
}
程序的输出是:
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
-1 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
所以"error"是加载文件后,数组第一个元素初始化为-1,而文件中只有20个5。 我真的不知道,谢谢你的帮助。
问题是您的 a.txt
看起来像这样:
55555555555555555555
所以当您再次尝试阅读它时,它确实而不是看起来像 20 个整数。它看起来像一个非常大的数字,对于整数来说太大了。
打印到文件时在每个整数之间添加一个space。像这样:
void save_file(char* filename) {
int i;
FILE* f;
f=fopen(filename, "w");
// Here you should check that f is valid before proceeding
for (i=0; i<row; i++)
fprintf(f, "%d ", a[i]);
// ^ notice
fclose(f);
}
此外,您应该始终检查 fopen
和 fscanf