Search code examples
cfilescanf

Reading from a file word by word


I have a custom archive structured as follows:

%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% contains names of files in archive
%dirs% contains names of directories
%content% lists file contents.

Since I need to print the content of a specified file, I want to read this archive word by word, in order to identify %content%tag and file name.

I know the existence of fscanf(), but it seems to work efficiently only if you know the archive pattern.

Is there a C library or command, like ifstream for C++, that allows me to read word by word?


Solution

  • You can just use fscanf to read one word at a time:

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

    If you don't know the maximum length of each word, you can use something similar to this answer to get the complete line, then use sscanf instead, using a buffer as large as the one created to read in the complete line. Or, you could use strtok to slice the read in line up into words.