c - 逐字读取文件

标签 c file scanf

<分区>

我有一个自定义存档,其结构如下:

%list% name1 name2 name3 %list%

%dirs% archive directories %dirs%

%content% name1 path1 content of file1 %content%
%content% name2 path2 content of file2 %content%
%content% name3 path3 content of file3 %content%

%list% 包含归档文件的名称
%dirs% 包含目录名称
%content% 列出文件内容。

因为我需要打印指定文件的内容,所以我想逐字读取这个存档,以便识别%content%标签和文件名。

我知道 fscanf() 的存在,但它似乎只有在您知道存档模式时才能有效地工作。

是否有 C 库或命令,如 C++ 的 ifstream,允许我逐字阅读?

最佳答案

您可以只使用fscanf 一次读取一个单词:

void read_words (FILE *f) {
    char x[1024];
    /* assumes no word exceeds length of 1023 */
    while (fscanf(f, " %1023s", x) == 1) {
        puts(x);
    }
}

如果你不知道每个单词的最大长度,你可以使用类似this answer的东西获取完整的行,然后使用 sscanf 代替,使用与创建的缓冲区一样大的缓冲区来读取完整的行。或者,您可以使用 strtok 将读取的行分割成单词。

关于c - 逐字读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16400886/

相关文章:

c - 二叉树 : user decides whether it should be a number tree or a word tree in c programming

c - 有关 scanf 和内存分配的帮助

c - scanf() 的问题

php - 使用 sscanf 读取固定长度的字符串

从 C 调用 Perl 函数会导致崩溃

c - 查找给定数字的所有质因数

c - 插入链表无法正常工作

c++ - 在 C++ 98 中优化 vector 过滤

python - 写入文件的更好方法?

python - 获取 Google App Engine 平台服务器文件夹中的静态文件列表