简体   繁体   English

fgets()在读取文件时导致分段错误

[英]fgets() causing segmentation fault when reading file

I'm trying to use fgets() to read text from a file and I keep getting a segmentation fault. 我正在尝试使用fgets()从文件中读取文本,并且不断出现分段错误。 The program reads in the entire file and then after it reads the last line it crashes. 该程序读取整个文件,然后在读取最后一行后崩溃。 Any help would be appreciated. 任何帮助,将不胜感激。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *readFile(FILE *);

char *readFile(FILE *file){
    int *outputSize = (int *)malloc(sizeof(int));
    (*outputSize) = 1024;
    char *buf = (char *)malloc(sizeof(char)*1024);
    char *output = (char *)malloc(sizeof(char)*(*outputSize));
    *output='\0';
    while(fgets(buf,1024,file)){
        if(strlen(output)+strlen(buf)+1>(*outputSize)){
            printf("REALLOCATING...");
            (*outputSize) *=2;
            output = realloc(output,sizeof(char)*(*outputSize));
        }
        printf("BUFFER SIZE: %d\nBUFFER : %s\n",strlen(buf),buf);
        strcat(output,buf);
        printf("OUTPUT SIZE: %d\nOUTPUT: %s\n",strlen(output),output);

    }
    printf("FREEING...");
    free(outputSize);
    free(buf);
    return output;
}

Your code is very hard to read, and therefore very hard to debug. 您的代码很难阅读,因此很难调试。 Which is why you're asking for help debugging it. 这就是为什么您需要帮助调试它的原因。

You don't need to read a file line-by-line when you know you're reading the whole file. 当您知道要读取整个文件时,无需逐行读取文件。 Simplify that code and just read the whole file - that makes it a lot easier to troubleshoot. 简化该代码,仅读取整个文件,这使故障排除变得更加容易。 (This code even has all error checking in less lines, and IMO is a LOT easier to understand, even without comments or debug statements that tell you what's going on) (此代码甚至可以在更少的行中进行所有错误检查,并且即使没有注释或调试语句来告诉您发生了什么,IMO还是很容易理解的)

char *readFile( FILE *file )
{
    struct stat sb;
    if ( !fstat( fileno( file ), &sb ) )
    {
        return( NULL );
    }

    if ( -1 == fseek( file, 0, SEEK_SET ) )
    {
        return( NULL );
    }

    char *data = malloc( sb.st_size + 1 );
    if ( data == NULL )
    {
        return( NULL );
    }

    /* this error check might not work in text mode because
       of \r\n translation */
    size_t bytesRead = fread( data, 1, sb.st_size, file );
    if ( bytesRead != sb.st_size )
    {
        free( data );
        return( NULL );
    }

    data[ sb.st_size ] = '\0';
    return( data );
}

Header files will need to be updated. 头文件将需要更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM