C 我写了一个函数,可以将整个文件读入一个字符串,但它不起作用

C 我写了一个函数,可以将整个文件读入一个字符串,但它不起作用,c,string,io,C,String,Io,所以,我需要将整个文件读入c语言中的字符串,我不知道文件会有多大。我编写了这个函数,但它不起作用: int slurp(char * filepath, char * outputfile) { fp = fopen(filepath, "r"); int success = 0; if (fp == NULL) { success = 1; } if (success == 0) { fseek(fp, 0, SEEK

所以,我需要将整个文件读入c语言中的字符串,我不知道文件会有多大。我编写了这个函数,但它不起作用:

int slurp(char * filepath, char * outputfile) {  
    fp = fopen(filepath, "r");
    int success = 0;
    if (fp == NULL) {
        success = 1;
    }
    if (success == 0) {
        fseek(fp, 0, SEEK_END);
        outputfile = (char *) calloc(ftell(fp) + 1, sizeof(char));
        fread(outputfile, ftell(fp), sizeof(char), fp);
        fseek(fp, 0, SEEK_SET);
        outputfile[ftell(fp)] = '\0';
    }
    return success;
}
int slurp(char * filepath, char * outputfile) {
    fp = fopen(filepath, "r");
    int success = 0;
    if (fp == NULL) {
        success = 1;
    }
    if (success == 0) {
        fseek(fp, 0, SEEK_END);
        size_of_file = ftell(fp);
        fseek(fp, 0, SEEK_SET);
        outputfile = (char *) calloc(size_of_file + 1, sizeof(char));
        fread(outputfile, size_of_file, sizeof(char), fp);
        outputfile[size_of_file] = '\0';
    }
    return success;
}
打开文件时不会出现错误,但当我打印输出文件时,只会得到(null)

为什么不起作用? 谢谢

我尝试了你的建议,但仍然不起作用:

int slurp(char * filepath, char * outputfile) {  
    fp = fopen(filepath, "r");
    int success = 0;
    if (fp == NULL) {
        success = 1;
    }
    if (success == 0) {
        fseek(fp, 0, SEEK_END);
        outputfile = (char *) calloc(ftell(fp) + 1, sizeof(char));
        fread(outputfile, ftell(fp), sizeof(char), fp);
        fseek(fp, 0, SEEK_SET);
        outputfile[ftell(fp)] = '\0';
    }
    return success;
}
int slurp(char * filepath, char * outputfile) {
    fp = fopen(filepath, "r");
    int success = 0;
    if (fp == NULL) {
        success = 1;
    }
    if (success == 0) {
        fseek(fp, 0, SEEK_END);
        size_of_file = ftell(fp);
        fseek(fp, 0, SEEK_SET);
        outputfile = (char *) calloc(size_of_file + 1, sizeof(char));
        fread(outputfile, size_of_file, sizeof(char), fp);
        outputfile[size_of_file] = '\0';
    }
    return success;
}

在阅读之前先查找到开头(与此顺序相反):


在阅读内容之前,你需要回到开头。“我不知道文件会有多大”——>如果文件大于
LONG\u MAX
LONG ftell(file*)
开始限制。但我怀疑OP是否关心大文件。旁白:没有理由调用
ftell(fp)
3x。一次就足够了。更好的是,对于最终的
outputfile[n]='\0';
使用
size\t n=fread()
的返回值。我编辑了问题,有编辑过的代码,但仍然不起作用可能
fp=fopen(filepath,“rb”);