gpt4 book ai didi

c - fgets() 读取文件时导致段错误

转载 作者:行者123 更新时间:2023-11-30 17:16:32 25 4
gpt4 key购买 nike

我正在尝试使用 fgets() 从文件中读取文本,但不断出现段错误。该程序读取整个文件,然后在读取最后一行后崩溃。任何帮助,将不胜感激。

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

最佳答案

您的代码很难阅读,因此很难调试。这就是您寻求帮助调试它的原因。

当您知道正在读取整个文件时,您不需要逐行读取文件。简化该代码并仅读取整个文件 - 这使得故障排除变得更加容易。 (此代码甚至在更少的行中进行了所有错误检查,并且 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 );
}

头文件需要更新。

关于c - fgets() 读取文件时导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29616734/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com