[英]fgets() causing segmentation fault when reading file
我正在嘗試使用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 );
}
頭文件將需要更新。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.