【发布时间】:2019-11-27 22:47:57
【问题描述】:
我在使用 fopen() 时遇到了段错误。我的代码如下。
void encoding(char otext[], char ibin[]){
//Some characters for storage:
char c, h, a, r;
unsigned int x;
//Check if file is available:
FILE *in;
FILE *out;
in = fopen("in.txt", "r");
if (in==NULL){
printf("Error: No input file\n");
exit(1);
}
out = fopen("out.txt", 'w');
if (out==NULL){
printf("Error: No output file\n");
exit(1);
}
//Scanning the file:
while(!feof(in)){//While not at the end of the in file
fscanf(in, "%c", &c);
fscanf(in, "%c", &h);
fscanf(in, "%c", &a);
fscanf(in, "%c", &r);
x = pack(c,h,a,r);
fprintf(out, "%u", x);
//fwrite(&x,sizeof(int),1,out);
}
//Close file
fclose(in);
fclose(out);
}
unsigned int pack(char c1, char c2, char c3, char c4){//Works
int bits = 8;
unsigned int x = c1;
x = (x << bits) | c2;
x = (x << bits) | c3;
x = (x << bits) | c4;
return x;
}
unsigned int encrypt(unsigned int x){//Works
int i = 0;
while (i < KEY){
unsigned int temp = x;
x = (x<<1);
if (temp > x){
x += 1;
}
i+=1;
}
return x;
}
我找到了这个主题:Segfault while using fopen - 这表明问题可能在于错误地使用 fprintf()。所以我注释掉了 fprintf() 行并简单地将其设置为打开和关闭,如下所示:
//Edit for clarity: I commented out everything BUT the 3 lines of
//code below, and I still got the segfault.
/*...*/
File *out;
out = fopen("out.txt", "w");
/*...*/
fclose(out);
即使这会导致段错误,让我相信问题不在于我使用 fprintf()。在这一点上,我不知所措。
【问题讨论】:
-
看看 valgrind。
-
也看看
feof() -
本网站使用问题/答案格式 -- 请不要编辑问题以在其中包含答案。您可以接受下面发布的答案,或者如果现有答案都不能解决您的问题,请发布您自己的答案
-
不是您的主要问题,而是:您对
feofin your while loop is wrong 的使用。您应该检查每个fscanf调用的返回值,如果返回值不是 1,则退出循环。