如何在 C++ 中从文件读取最后一个字节
使用 fseek(),偏移量为 -1,模式为 SEEK_END:
how-to-read-last-byte-from-file-in-c.cpp
fseek(myfile, -1, SEEK_END);即用型函数
read_last_byte_function.cpp
#include <cstdio>
#include <optional>
/**
* 读取给定文件的最后一个字节
*/
std::optional<char> readLastByteOfFile(const char* filename) {
FILE* fin = fopen(filename, "r");
if(fin == nullptr) {
return std::nullopt;
}
fseek(fin, -1, SEEK_END);
char lastByte;
if(fread(&lastByte, 1, 1, fin) == 0) {
return std::nullopt;
}
fclose(fin);
return lastByte;
}完整示例程序
read_last_byte_full_example.cpp
#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <optional>
/**
* 读取给定文件的最后一个字节
*/
std::optional<char> readLastByteOfFile(const char* filename) {
FILE* fin = fopen(filename, "r");
if(fin == nullptr) {
return std::nullopt;
}
fseek(fin, -1, SEEK_END);
char lastByte;
if(fread(&lastByte, 1, 1, fin) == 0) {
return std::nullopt;
}
fclose(fin);
return lastByte;
}
int main(int argc, char** argv) {
if(argc < 2) {
std::cerr << "Usage: " << argv[0] << " <input file to read from>" << std::endl;
}
auto lastByte = readLastByteOfFile(argv[1]);
if(lastByte) {
std::cout << lastByte.value() << std::endl;
} else {
std::cout << "File error or empty" << std::endl;
}
}使用以下命令生成测试数据:
generate_test_files.sh
echo -n "abcd" > test.txt
touch test2.txt使用以下命令编译:
compile_read_last_byte.sh
g++ -o read-last-byte read-last-byte.cpp --std=c++17使用以下命令测试:
read_last_byte_test_output.txt
$ ./test-last-byte test1.txt
d
$ ./test-last-byte test2.txt
File error or no last byteCheck out similar posts by category:
C/C++
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow