fread 读取文件末尾
fread reading past the end of file
为了熟悉Code::Blocks,我写了一些简单的代码来用C读取一个文件的内容并输出到命令行。我只是从我编写的另一个程序中复制了这段代码(完全可以正常工作)。
我打开文件,malloc 足够的内存来存储文件的内容,然后将文件的内容读入那块内存。当我打印文件的内容时,最后会出现随机垃圾。我添加了一些调试打印语句来检查文件的长度(在 15 处出现)和我将文件内容读入的字符串的长度(在 22 处出现)。我不明白为什么我读入数据的字符串比文件长?
感谢任何帮助,代码如下。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
//open a file for editing
FILE * inputFile = fopen("hexfile.txt", "rb");
//Measure the file and allocate memory
fseek(inputFile, 0, SEEK_END);
unsigned long fileSize = ftell(inputFile);
rewind(inputFile);
char *inputData = (char*)malloc(fileSize);
//Save the contents of the file to a variable
fread(inputData, sizeof(char), fileSize, inputFile);
printf("File Size: %lu \n", fileSize);
int length = strlen(inputData);
printf("String Length = %d \n", length);
printf("Contents of file: %s", inputData);
//Close files
fclose(inputFile);
return 0;
}
你的程序几乎是正确的。要有一个有效的字符串,它必须是
终止于 '[=11=]'
。如果您的文件没有空字节
巧了,那么你的数据读成字符串就没完没了
要解决此问题,只需在分配内存时再添加一个 space,并设置
最后一个字节为空:
char *inputData = (char*)malloc(fileSize+1);
/* ... */
inputData[fileSize] = '[=10=]';
为了熟悉Code::Blocks,我写了一些简单的代码来用C读取一个文件的内容并输出到命令行。我只是从我编写的另一个程序中复制了这段代码(完全可以正常工作)。
我打开文件,malloc 足够的内存来存储文件的内容,然后将文件的内容读入那块内存。当我打印文件的内容时,最后会出现随机垃圾。我添加了一些调试打印语句来检查文件的长度(在 15 处出现)和我将文件内容读入的字符串的长度(在 22 处出现)。我不明白为什么我读入数据的字符串比文件长?
感谢任何帮助,代码如下。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
//open a file for editing
FILE * inputFile = fopen("hexfile.txt", "rb");
//Measure the file and allocate memory
fseek(inputFile, 0, SEEK_END);
unsigned long fileSize = ftell(inputFile);
rewind(inputFile);
char *inputData = (char*)malloc(fileSize);
//Save the contents of the file to a variable
fread(inputData, sizeof(char), fileSize, inputFile);
printf("File Size: %lu \n", fileSize);
int length = strlen(inputData);
printf("String Length = %d \n", length);
printf("Contents of file: %s", inputData);
//Close files
fclose(inputFile);
return 0;
}
你的程序几乎是正确的。要有一个有效的字符串,它必须是
终止于 '[=11=]'
。如果您的文件没有空字节
巧了,那么你的数据读成字符串就没完没了
要解决此问题,只需在分配内存时再添加一个 space,并设置 最后一个字节为空:
char *inputData = (char*)malloc(fileSize+1);
/* ... */
inputData[fileSize] = '[=10=]';