fopen导致分段错误

时间:2019-11-27 22:47:57

标签: c printf scanf

我正在使用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()的使用。这时我很茫然。

1 个答案:

答案 0 :(得分:2)

这是您的问题。您正在传递字符而不是字符串。

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);
}