如何在不遍历内容的情况下查找文件中的字符数

Spe*_*ine 7 c++ file-io file-read

在一个项目中,我必须读取一个文件,并且我必须处理文件中的字符数,并且有一种方法可以获得字符数而无需逐个字符地读取它(否则我将不得不读取文件两次,一次只是为了找到它中的字符数).

它甚至可能吗?

Mar*_*ork 11

是.

寻求到最后获得结束的位置即大小.

FILE*  file = fopen("Plop");
fseek(file, 0, SEEK_END);
size_t  size = ftell(file);      // This is the size of the file.
                                 // But note it is in bytes.
                                 // Also note if you are reading it into memory this is
                                 // is the value you want unless you plan to dynamically
                                 // convert the character encoding as you read.

fseek(file, 0, SEEK_SET);        // Move the position back to the start.
Run Code Online (Sandbox Code Playgroud)

在C++中,流具有相同的功能:

std::ifstream   file("Plop");
file.seekg(0, std::ios_base::end);
size_t size = file.tellg();

file.seekg(0, std::ios_base::beg);
Run Code Online (Sandbox Code Playgroud)


das*_*ght 8

你可以试试这个:

FILE *fp = ... /*open as usual*/;
fseek(fp, 0L, SEEK_END);
size_t fileSize = ftell(fp);
Run Code Online (Sandbox Code Playgroud)

但是,这将返回文件中的字节数,而不是字符数.除非已知编码是每个字符一个字节(例如ASCII),否则它是不一样的.

在学习了大小之后,您需要将文件"倒回"到开头:

fseek(fp, 0L, SEEK_SET);
Run Code Online (Sandbox Code Playgroud)