0

If I`ve got a TXT file with a pre-determined structure, is there any way I can read some of the text directly from the file without having to parse or tokenize a string? For instance, if I have the following code:

#include <stdlib.h>
#include <stdio.h>
#include <cstring>
#include <fstream>

int main(int argc, char** argv) {
    FILE* test = fopen("test.txt","w+");
    char* read;
    fprintf(test,"(foo,_TEMP71_,_,_)\n");
    fprintf(test,"(foo,_TEMP52_,_,_)\n");
    fprintf(test,"(foo,_TEMP43_,_,_)\n");
    fprintf(test,"(foo,_TEMP24_,_,_)\n");
    fprintf(test,"(foo,_TEMP15_,_,_)\n");
    fprintf(test,"(foo,_TEMP06_,_,_)\n");
    fseek(test, 0, SEEK_SET); //returns the file pointer to start of file

    while(feof(test) == 0)
    {
        fscanf(test, "_%s_", read); //or fscanf(test, "_TEMP%s_", read);
        printf("%s\n", read);
    }

    fclose(test);

}

Note that on the fscanf line, I read from this website that you could specify a certain string of characters to be read, but I don`t think I understood quite how it works.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Pedro
  • 333
  • 1
  • 5
  • 24
  • 1
    Try `char read[32];`... `while(fscanf(test, "%*[^_]_%31[^_]%*[^\n]%*c", read) != EOF) { printf("%s\n", read); }` – BLUEPIXY May 23 '17 at 22:53
  • Almost there, I would like to keep the underscores (this way gets me TEMP71, TEMP52, and I would like \_TEMP71\_), if at all possible. If its not possible, its an easy fix, I'll just use sprintf. Also, would you mind explaining that a little bit for me? – Pedro May 23 '17 at 22:56
  • In the example above `_` can not be included. `%*[^_]` Skip up to `_`. `%31[^_]` Read up to `_`. Also `read` requires an area to read. – BLUEPIXY May 23 '17 at 23:01
  • 1
    And Read [Why is “while ( !feof (file) )” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – BLUEPIXY May 23 '17 at 23:02
  • If the record is fixed length and in the same format, you can do as follows. `char read[9] = {0};`...`while(fscanf(test, "%*5c%8c%*[^\n]%*c", read) != EOF)` – BLUEPIXY May 23 '17 at 23:06
  • @BLUEPIXY thanks so much. I will stop using feof from now on. Can you point me to where/how you knew about the formated reading? And for the record, the record is not a fixed lenght, but is the same format which is: `(operation,_temp1_,_temp2_,_temp3_)` – Pedro May 23 '17 at 23:13
  • if `temp2` or `temp3` exists or does not exist, It is probably impossible for a single `fscanf` to extract them. – BLUEPIXY May 23 '17 at 23:18
  • @BLUEPIXY got it! I will keep that in mind. My initial approach was to tokenize the full line using the commas as tokens, but I thought that a single `fscanf` could do it all – Pedro May 23 '17 at 23:22

0 Answers0