【问题标题】:fopen causes a segmentation faultfopen 导致分段错误
【发布时间】: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()
  • 本网站使用问题/答案格式 -- 请不要编辑问题以在其中包含答案。您可以接受下面发布的答案,或者如果现有答案都不能解决您的问题,请发布您自己的答案
  • 不是您的主要问题,而是:您对feof in your while loop is wrong 的使用。您应该检查每个 fscanf 调用的返回值,如果返回值不是 1,则退出循环。

标签: c printf scanf


【解决方案1】:

这是你的问题。你传递的是一个字符而不是一个字符串。

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

【讨论】:

  • 天哪。那行得通。谢谢你,我讨厌自己。
  • + 执行#include &lt;stdio.h&gt;,这样您就会收到指向此方向的警告。
  • 无论有没有#include &lt;stdio.h&gt;,您都应该收到警告。没有它,fopen 是未声明的,并且从 C99 开始,C 不允许调用未声明的函数。在添加#include 之前,请弄清楚如何调用您的编译器,以便它会就此向您发出警告。 @PSkocik
  • ^ 最好调用编译器,以便它给出关于此的错误。有些人认为警告不重要
  • 我建议使用标志-Wall -Werror进行编译。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-06
  • 2020-12-31
  • 2019-07-21
  • 2018-07-28
  • 2014-04-25
  • 2011-07-18
相关资源
最近更新 更多