Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read data from file till end of line in C/C++

Tags:

c

eol

eof

fopen

It is common to read until end of file, but I am interested in how could I read data (a series of numbers) from a text file until the end of a line? I got the task to read several series of numbers from a file, which are positioned in new lines. Here is an example of input:

1 2 53 7 27 8
67 5 2
1 56 9 100 2 3 13 101 78

First series: 1 2 53 7 27 8

Second one: 67 5 2

Third one: 1 56 9 100 2 3 13 101 78

I have to read them separately from file, but each one till the end of line. I have this code:

    #include <stdio.h>
    FILE *fp;
    const char EOL = '\\0';
    void main()
    {
        fp = fopen("26.txt", "r");
        char buffer[128];
        int a[100];
        int i = 0;
        freopen("26.txt","r",stdin);
        while(scanf("%d",&a[i])==1 && buffer[i] != EOL)
             i++;
        int n = i;
        fclose(stdin);
     }  

It reads until the end of the file, so it doesn't do quite what I would expect. What do you suggest?

like image 419
Eszter Avatar asked Dec 22 '12 10:12

Eszter


People also ask

How do I read end of file?

feof() The function feof() is used to check the end of file after EOF. It tests the end of file indicator. It returns non-zero value if successful otherwise, zero.

How do you end a line in C?

In most C compilers, including ours, the newline escape sequence '\n' yields an ASCII line feed character. The C escape sequence for a carriage return is '\r'.

What is EOF in C programming?

The End of the File (EOF) indicates the end of input. After we enter the text, if we press ctrl+Z, the text terminates i.e. it indicates the file reached end nothing to read.


2 Answers

Use fgets() to read a full line, then parse the line (possibly with strtol()).

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

int main(void) {
  char buffer[10000];
  char *pbuff;
  int value;

  while (1) {
    if (!fgets(buffer, sizeof buffer, stdin)) break;
    printf("Line contains");
    pbuff = buffer;
    while (1) {
      if (*pbuff == '\n') break;
      value = strtol(pbuff, &pbuff, 10);
      printf(" %d", value);
    }
    printf("\n");
  }
  return 0;
}

You can see the code running at ideone.

like image 200
pmg Avatar answered Sep 21 '22 12:09

pmg


The \n should be the escape for new line, try this instead

const char EOL = '\n';

did u get it working? this should help:

#include <stdio.h>
FILE *fp;
const char EOL = '\n'; // unused . . .

void main()
{
    fp = fopen("26.txt", "r");
    char buffer[128];
    int a[100];
    int i = 0;
    freopen("26.txt","r",stdin);

    while(scanf("%i",&a[i])==1 && buffer[i] != EOF)
        ++i;

    //print values parsed to int array.    
    for(int j=0; j<i; ++j)
        printf("[%i]: %i\n",j,a[j]);

    fclose(stdin);
}  
like image 29
rbtLong Avatar answered Sep 22 '22 12:09

rbtLong