1

I'm working on a task where I need to read a long .txt file. The first line contains the number of lines the .txt file has, the rest of the lines follow the same structure, "int int int char:char".

How do I read the first line separately from the rest?

I wrote the following code:

FILE *fajl;
falj = ("musor.txt", "r");

while (!feof(fajl) && fajl > 1)
    {
        fscanf_s(fajl, "%d %d %d %[^:]c:%c\n", &tomb[i].ado, &tomb[i].perc, &tomb[i].masodperc, &tomb[i].eloado, &tomb[i].cim);
        i++;
    }

Sorry for the unknown words, the variable names are in Hungarian.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • Put your first `fscanf_s` call before the loop and read in using a format appropriate to that first line. Then use a `for` loop to read in however many lines you need. Also, there is something important missing from `falj = ("musor.txt", "r");` ... the name of the `fopen` function. – Adrian Mole Jun 20 '21 at 21:19
  • 2
    Also, don't use feof as a while condition - use fscanf or fgets: https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong – Jerry Jeremiah Jun 20 '21 at 21:22
  • 1
    Also, `fajl > 1` can't possibly be right because fopen doesn't return an integer and fajl is a pointer to a FILE object. It should be `fajl != NULL` – Jerry Jeremiah Jun 20 '21 at 21:24
  • If this is MS VC the call to `fscanf_s(fajl, ...);` is lacking a length argument for the `%[]` and `%c` format specifiers. You must specify the sizes for all c, C, s, S, or string control set [] parameters, by passing additional arguments. No compiler warning? And what is the `c` for in `%[^:]c:`? – Weather Vane Jun 20 '21 at 21:57
  • ...also you should not have `\n` at the end of the `fscanf_s` format string. – Weather Vane Jun 20 '21 at 22:05
  • For line-based input, I recommend that you use [`fgets`](https://en.cppreference.com/w/c/io/fgets) instead of `fscanf_s`. You can then use [`sscanf`](https://en.cppreference.com/w/c/io/fscanf) on the returned line input. – Andreas Wenzel Jun 20 '21 at 22:30

1 Answers1

0

So this is basically just the collection of all the comments from the question.

//-------------------------
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct Tomb
{
    int masodperc, eloado, ado, perc;
    char cim;  
};
typedef struct Tomb Tomb;
//-------------------------

int main(int argc, char *argv[])
{
    char linesLength[10], stringFajl[100];
    FILE *fajl;
    fajl = fopen("musor.txt", "r");
    if(fgets(linesLength, 100, fajl)==NULL || fajl == NULL) //first line read
    {
        printf("error\n");
        return -1;
    }
    int length = atoi(linesLength), i=1;
    Tomb tomb[length];
    while (fgets(stringFajl, 100 ,fajl )!=NULL || i<=length)
    {
        sscanf(stringFajl, "%d %d %d %d [^:]c:%c", &tomb[i].ado, &tomb[i].perc, &tomb[i].masodperc, &tomb[i].eloado, tomb[i].cim);
        i++;
    }
    fclose(fajl);
    return 0;
}
Miraz
  • 343
  • 3
  • 15