开发者

How to detect a new line of any file using C program

I am reading a file of integers. I want to save integers from each line to a new array.开发者_StackOverflow For this I want to detect a new line of a file. If anybody knows this please help.

The file to be read is as follows

1 2 4 5 6
7 3 2 5 
8 3 
9 7 6 2 


Why not use fgets() to get one line at a time from the file? You can then use sscanf() instead of fscanf() to extract the integers.


#include <stdio.h>
int main ( int argc, char **argv ) {
    FILE *fp = fopen ( "d:\\abc.txt", "r");
    char line[1024];
    char ch = getc ( fp );
    int index = 0;
    while ( ch != EOF ) {
        if ( ch != '\n'){
            line[index++] = ch;
        }else {
            line[index] = '\0';
            index = 0;

            printf ( "%s\n", line );
        }
        ch = getc ( fp );
    }


    fclose ( fp );

    return 0;
}


Use fgets() to read a single line of input at a time. Then use strtol() to parse off an integer, using its "end pointer" feature to figure out where to try again, and loop until you've parsed all the values.


Using getc() for this action is fine but do not forget that getc() returns type is int. Retype to char "works" but you can have a problem with non strict-ASCII input file because EOF = -1 = 0xFF after retype to char (on most C compilers), i.e. 0xFF characters are detected as EOF.


#include<stdio.h>
void main()
{
    FILE *p;
    int n;
    int s=0;
    int a[10];
    p=fopen("C:\\numb.txt","r");
    if(p!=NULL)
        printf("file opened");

    while((n=getc(p))!=EOF)
    {   if(n!=NULL && n!='\n')
      {
        printf("\n%d",n);
        a[s]=n;
        ++s;
      }
    }
fclose(p);
getchar();
}

I'm not sure of the int to char and vice versa conversion but program works for non zero numbers. I tried on visual basic.


If you use reading char by char then recognizing whitespace with '32' and 'enter' by '13' and/or '10'

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜