[英]read a file into a buffer, but program crashes at fread after calling fseek
我想将文件读入缓冲区。 我在fread()
遇到分段错误。 看起来ftell()
给出了正确的大小。 但是后来出了问题。 fseek()
修改f
吗? 为什么fread()
不起作用?
int pk_load_file( const char *filename )
{
FILE *f;
int size;
unsigned char *buf;
if( ( f = fopen( filename, "rb" ) ) == NULL )
return -1;
fseek( f, 0, SEEK_END );
if( ( size = ftell( f ) ) == -1 )
{
fclose( f );
return -2;
}
fseek( f, 0, SEEK_SET );
if( fread( buf, 1, size, f ) != size )
{
fclose( f );
return -3;
}
fclose( f );
return( 0 );
}
正确的代码:
#include <stdio.h>
#include <stdlib.h>
int pk_load_file( const char *filename ) {
FILE *f;
int size;
unsigned char *buf;
if ((f = fopen(filename, "rb")) == NULL) {
return -1;
}
fseek(f, 0, SEEK_END);
if ((size = ftell(f)) == -1) {
fclose(f);
return -2;
}
buf = malloc(size); // here is the magic. you need to allocate "size" bytes
if (buf == NULL) {
fclose(f);
return -3;
}
fseek(f, 0, SEEK_SET);
if (fread(buf, 1, size, f) != size) {
fclose(f);
return -4;
}
fclose(f);
return 0;
}
unsigned char *buf;
如上所述,答案给出了未定义的行为,因此可以使用动态分配或将其声明为数组,
#define MAX_LENGTH 1024
unsigned char buf[MAX_LENGTH];
并将其传递给fread()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.