如何使用C++一次读取整个二进制文件
how to read a whole binary file at a time with C++
我在文件中有一些二进制数据。为了读取所有数据,我这样做了:
// open the file
// ...
// now read the file
char data;
while (fread(&data, sizeof(char), 1, input) == 1) {
// do something
}
嗯,这工作得很好,但我的老师说我不应该逐行读取文件,因为这会增加 I/O 的数量。所以现在我需要一次读取整个二进制文件。我该怎么做?谁能帮忙?
unsigned long ReadFile(FILE *fp, unsigned char *Buffer, unsigned long BufferSize)
{
return(fread(Buffer, 1, BufferSize, fp));
}
unsigned long CalculateFileSize(FILE *fp)
{
unsigned long size;
fseek (fp,0,SEEK_END);
size= ftell (fp);
fseek (fp,0,SEEK_SET);
if (size!=-1)
{
return size;
}
else
return 0;
}
此函数读取文件并将其存储到缓冲区中,因此访问缓冲区可减少 IO 时间:
int main()
{
FILE *fp = fopen("Path", "rb+");// i assume reading in binary mode
unsigned long BufferSize = CalculateFileSize(fp);//Calculate total size of file
unsigned char* Buffer = new unsigned char[BufferSize];// create the buffer of that size
unsigned long RetValue = ReadFile(fp, Buffer, BufferSize);
}
首先请注意,如果将文件读取到 1 字节缓冲区(代码中的数据变量(,则程序可能会崩溃(如果文件大小> 1(。因此,您需要分配一个缓冲区来读取文件。
FILE *f = fopen(filepath, "rb+");
if (f)
{
fseek(f, 0L, SEEK_END);
long filesize = ftell(f); // get file size
fseek(f, 0L ,SEEK_SET); //go back to the beginning
char* buffer = new char[filesize]; // allocate the read buf
fread(buffer, 1, filesize, f);
fclose(f);
// Do what you want with file data
delete[] buffer;
}
相关文章:
- 在一次迭代中从 txt 文件中读取多行
- 如何使用C++一次读取整个二进制文件
- 蓝牙插座只能读取一次,为什么?
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- 如何从文本文件中一次读取一个字符
- 尝试一次将单个字符读取到大小不确定的数组中
- 为什么我的 cout 一次执行,尽管 cin 应该在两者之间读取?
- 无法一次从二进制文件中读取一个 int
- 一次读取一个字节的 unicode
- 一次读取一个字符的文件,直到使用 read(2) 和 write(2) 换行符
- 快速简单的方法,以C++为单位一次读取一个字节的 stdin
- 尝试一次读取一个字符的矩阵
- 我如何一次读取和写3位
- 一次从二进制读取 4 个字节(C++)
- 输入迭代器可以重复读取,而输出迭代器只能写入一次
- 如何创建在 c++ 中只读取一次的初始化函数
- 缓冲的 std::ifstream 只能从磁盘读取一次 (C++)
- QTcpSocket每~0.5s才读取一次数据,即使是非常小的数据包,任何方法都可以加快速度
- 我可以(a)不通过输入迭代器写入,或者(b)只通过一个迭代器读取一次吗?
- C++ 从键盘读取一次一个字符,直到用户输入字母("A.."Z"或"a".."z')