0

So I was trying to think of a way to get the first number of each line from a file in C.

Example;

100 2 4 5 7 8

102 3 4 5 6 7

400 6 7 9 9 3

420 5 7 3 6 3

And I want to have the array[5]

array[5] = {100, 102, 400, 420}

arrrayb[5] = {2, 3, 6, 5}

arrayc [5] = {4 5 7 8, 4 5 6 7, 7 9 9 3, 7 3 6 3}

So far I have a way to count the number of lines;

  while ((c = fgetc (file)) != EOF)
  {
    if(c=='\n'){
      nlines++;
    }
  }

Thank you

  • 2
    It's unclear what you want in arrayc, do you want an array of strings with the last 4 numbers each with spaces? Do you want a 2D array with the last 4 numbers of each line per line? – anastaciu Apr 05 '20 at 23:57
  • Processing lines with `fgetc()` is usually wrong — or, at least, suboptimal. You'd do far better using `fgets()` or POSIX `getline()`. All else apart, they deal with buffer overflow — a line that is too long. Your loop doesn't even stash the data anywhere; it isn't clear how you think that is going to help with your real task. Using `fgets()` followed by `sscanf()` is probably correct. What is open to debate is the format that the contents of `arrayc` takes — is it an array of strings, or is it some sort of 2D array of integers? And is the number items after the first two numbers fixed? – Jonathan Leffler Apr 06 '20 at 01:02
  • while ((c = getline(&buffer, &buffersize, file)) != -1) { nlines++; } – whatthecode Apr 06 '20 at 15:01

1 Answers1

-1

assume you have allocated array/arrayb and arrayc with sufficient space:

  int tmp[6]={0};
  int count=0;
  while (!feof(file)) {
      if(fscanf(file, "%d %d %d %d %d %d", tmp,tmp+1,tmp+2,tmp+3,tmp+4,tmp+5)==6){
          array[count] =tmp[0];
          arrayb[count]=tmp[1];
          arrayc[(count<<2)]  =tmp[2];
          arrayc[(count<<2)+1]=tmp[3];
          arrayc[(count<<2)+2]=tmp[4];
          arrayc[(count<<2)+3]=tmp[5];
          count++;
      }
  }
FangQ
  • 1,444
  • 10
  • 18
  • 1
    [Why is "while ( !feof (file) )" always wrong](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – Shawn Apr 06 '20 at 00:07
  • like it or not, it is a valid solution, you should not down-vote. my test `fscanf()==6` has mitigated the side-effect of `while(!feof())` if you really care. – FangQ Apr 06 '20 at 00:19
  • It's broken. What if `fscanf()` returns a value less than 6 because of a failed conversion, not because it's at the end of the file? – Shawn Apr 06 '20 at 01:00