put data into buffer in C
Hi I'm reading data from a file put it in the buffer. Now I read the data from the file and got it in the buffer, but somehow the buffer is filled with some junk. In fact, I get the code from http://www.cplusplus.com/reference/clibrary/cstdio/fread/.I always get the result Reading Error and when I check the size of the lSize and result , they two are not the same.I'm new to C or C++.Can somebody help me? I tag both C and C++ since I don't know which one is the correct one. Sorry.
FILE *data_fp, *keyFile;
long lSize;
int i,j;
char hvalue[21];
char dt[300];
uint64_t insert_key;
data_fp = fopen("./aaa", "r+");
if (data_fp == NULL) {
printf("fopen aaa error\n");
exit(-1);
}
// obtain file size:
fseek (data_fp , 0 , SEEK_END);
lSize = ftell (data_fp);
rewind (data_fp);
// allocate memory to contain the whole file:
buffe开发者_开发知识库r = (char*) malloc (sizeof(char)*lSize);
if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}
size_t result = fread (buffer,1,lSize,data_fp);
if (result != lSize) {fputs ("Reading error",stderr); exit (3);}
puts(buffer);
data_fp = fopen("./aaa", "rb");
Your file is open in text mode. Using ftell()
to determine the length of a file open in text mode is not portable, and doesn't necessarily work.
fread()
may return a short item count if either end-of-file is reached, or an error occurs. You must use feof()
/ ferror()
to determine which is the case:
size_t result = fread(buffer, 1, lSize, data_fp);
if (result != lSize) {
if (ferror(data_fp)) {
perror("Reading error");
exit (3);
}
/* End-of-file reached, so adjust file size downward */
lSize = result;
}
(Using perror()
will mean that if an error is occuring, you will see what it is).
Note also that the data read from the file is not necessarily nul-terminated, so you cannot just pass it to puts()
. You must add a nul-terminator:
buffer[lSize] = 0;
This will also require allocating a single additional byte:
buffer = (char*) malloc (lSize + 1);
(sizeof(char)
is defined to be 1
, so it is not necessary here).
精彩评论