cfilescanffgets

Using scanf to Read and Store Values from a File in C


I have a file that contains data in a specific format, and I want to extract and store certain numbers from that file. in the program I initially used sscanf to parse and store values from the file, and it worked well. However, I'm told I am not allowed to use sscanf, fscanf or any other library functions at all. the only two functions I am allowed to use are scanf and fgets to achieve this and then I should manually convert the string values to integer myself (Which is not the problem). I am frustrated because it seems like scanf was not designed to be used this way at all without using other library functions, is there something I am missing? I would appreciate it if you could show me how this can be achieved.

This is the the part of the code that I need help with (assume the file is opened and is being read and a line is stored in buffer):

char str1[5], str2[5];
if (scanf(buffer, "test1 %s, test2%s", str1, str2) == 2) {
    printf("Success");
}

I think the scanf is waiting for keyboard input and doesn't read the line that is in the buffer.

This is the line I have in my file and the program is supposed to skip the test1 and test2 and pick up the numbers in front of them (4 and 5) and store them in str1 and str2:

test1 4, test25


Solution

  • Use fgets() to read a line from the file into a buffer as a string. Then parse the string.

    It is not too much code to write your own sscanf() with limited matching functionality.

    Below is untested sample code to get OP started.

    #define BUF_N 5
    
    int my_scanf2(const char *buffer, const char *fmt, char *str1, char *str2) {
      if (buffer == 0 || fmt == 0 || str == 0 || str2 == 0) {
        return EOF;
      }
      char *s[] = { str1, str2 };
      int count = 0;
      while (*fmt) {
        if (*fmt == '%') {
          fmt++;
          if (*fmt != 's' || count == 2) {
            return EOF;
          }
          unsigned len = 0;
          while (my_iswhitespace(*buffer)) {
            buffer++;  
          }
          while (len < BUF_N-1 && *buffer && !my_iswhitespace(*buffer)) {
            s[count][len++] = *buffer++;
          }
          if (len == 0) {
            return count;
          }
          s[count][len] = '\0';
          count++;
        } else if (*fmt == *buffer) {
          buffer++;  
        } else {
          return count;
        }
        fmt++;
      }
      if (*fmt) {
      return count;
    }
    
    // Usage
    if (my_scanf2(buffer, "test1 %s, test2%s", str1str1, str2) == 2) {
        printf("Success");
    }