首页 > 解决方案 > getc 和 fgetc 不起作用...给出分段错误

问题描述

我正在尝试将一个文件的内容复制到另一个文件中。在我完成之前,我想在屏幕上打印内容以查看一切是否正常。但他们没有。

包括我...

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

我的代码是...

void decodeBin(char * filename){
    //opens  filename for reading and outfilename for writing
    FILE * input = fopen(filename, "r");

    char file_name[] = "";
    strcpy(file_name, filename);
    char out_file[] = "out";
    strcat(out_file, file_name);
    FILE * output = fopen(out_file, "w");


    char ch;
    if (input != NULL){
        while((ch = fgetc(input)) != EOF)
        printf("%c", ch);
    }

    fclose(input);
    fclose(output);
}

我查看了其他堆栈溢出帖子,其中建议检查文件指针是否不为空,我这样做了。怎么了?

标签: cfilepointers

解决方案


通过在file_nameandout_file数组的范围之外写入会导致未定义的行为。当您没有为数组指定大小时,大小由您用来初始化它的字符串确定。所以它相当于

char file_name[1] = "";
char out_file[4] = "out";

额外的字节用于尾随的空值。

由于您没有为要复制到其中的字符串声明足够大的数组,因此您会得到未定义的行为。

您需要声明数组的大小足以容纳最大可能的文件名。或者malloc()根据参数来调整它的大小。

不需要file_name变量,因为它只是 的副本filename,您可以直接使用它。

char *outfile = malloc(strlen(filename) + sizeof("out"));
sprintf(outfile, "out%s", filename);

然后在函数结束时,执行

free(outfile);

推荐阅读