getc和fgetc无法正常工作……给出分段错误

问题描述 投票:0回答:1

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

我包括...

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

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

c file pointers
1个回答
1
投票

[通过在file_nameout_file数组的边界之外写入导致了不确定的行为。当您不为数组指定大小时,该大小由用于初始化它的字符串确定。因此等效于

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

额外的字节用于尾随的null。

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

您需要声明足够大的数组以容纳最大的文件名。或使用malloc()根据参数调整大小。

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

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

然后在函数末尾,执行

free(outfile);
© www.soinside.com 2019 - 2024. All rights reserved.