温馨提示×

C++ fseek 在二进制文件中应用

c++
小樊
89
2024-07-15 17:42:46
栏目: 编程语言

在C++中,可以使用fseek函数来在二进制文件中移动文件指针的位置。fseek函数的原型如下:

int fseek(FILE *stream, long int offset, int origin);

其中,stream是指向要在其上进行移动操作的文件流的指针;offset是要移动的字节数;origin指定了移动操作的起始位置,可以是SEEK_SET(文件起始位置)、SEEK_CUR(当前位置)或SEEK_END(文件末尾位置)。

下面是一个简单的示例,演示如何使用fseek在二进制文件中移动文件指针的位置:

#include <iostream>
#include <fstream>

int main() {
    std::ifstream file("example.bin", std::ios::binary);

    if (!file) {
        std::cerr << "Failed to open file." << std::endl;
        return 1;
    }

    // Move file pointer to the 5th byte from the beginning
    fseek(file, 4, SEEK_SET);

    // Read and print the next byte
    char nextByte;
    file.read(&nextByte, 1);
    std::cout << "Next byte: " << nextByte << std::endl;

    file.close();

    return 0;
}

在上面的示例中,首先打开了一个名为example.bin的二进制文件,然后使用fseek函数将文件指针移动到文件的第5个字节处。接着读取并打印了下一个字节的内容。

0