[英]fopen causes a segmentation fault
我正在使用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;
}
我找到了這個主題: 使用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()的使用。 在這一點上我很茫然。
這是你的問題。 您傳遞的是char而不是字符串。
out = fopen("out.txt", 'w');
if (out==NULL){
printf("Error: No output file\n");
exit(1);
}
將'w'
替換為"w"
。 這是正確的版本。
out = fopen("out.txt", "w");
if (out==NULL){
printf("Error: No output file\n");
exit(1);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.