How to read tab delimited integer text file in C?

I have a file with integer integer delimiters (a .txt file), and I want to read them using only C, line by line. So let's say each line has 5 integers. How can i do this?

My first attempt was as follows. It was just for reading in one whole, but even this did not work:

    FILE *fp;
    char blah[255];
    int *some_int;
fp = fopen("test.txt", "rt");
while (fgets(blah, 255, fp) != NULL)
{
    sscanf(blah, "%d", some_int);
    printf("%d\n", *some_int);
}
+3
source share
3 answers

Here is a path that no one else has suggested that doesn't use fscanfso that you can have the correct error handling:

char buffer[BUFSIZE];
size_t size = 5;
int *data = malloc(size * sizeof *line);

if(line == NULL) error();

while(fgets(buffer, sizeof buffer, fp)
  {
    size_t i = 0;
    char *next = buffer;
    while(*next && *next != '\n')
      {
        data[i++] = strtol(next, &next, 0);
        // check for errors
      }
  }

, , *scanf "%d" , , () : strtol. *scanf , , " " , strtol , , .

- . :

  • i == size, data realloc. , , , , .
  • fgets (, '\0' '\n'). , , . - , , - fgets, , . ( fgets.)
  • - , .
+3
#include <stdio.h>
int main(){
    FILE *fp;
    int scanned = 0;
    int some_ints[5];
    fp = fopen("test.txt", "r");
    while ((scanned = fscanf(fp, "%d %d %d %d %d", some_ints, some_ints+1, some_ints+2, some_ints+3, some_ints+4)) !=  EOF) {
        if(scanned ==5){
            printf("%d %d %d %d %d\n", some_ints[0], some_ints[1], some_ints[2], some_ints[3], some_ints[4]);
        }
        else {
            printf("Whoops! Input format is incorrect!\n");
            break;
        }
    } 
}
+2

I would do something like this:

int storedVals[MAX_STORED_VALS];
int bf;
int ii=0;

while (!feof(fp) && ii<MAX_STORED_VALS) {
  if (fscanf(fp," %d",&bf)) {
    storedVals[ii++]=bf;
  }
}

fscanf automatically truncates the space. Thus, as long as there is a space in the scan line, it will get rid of zero or more \ t (tabs) and \ n (new lines) to find the next integer. Of course, this does not greatly affect bug fixes.

+1
source

All Articles