Reputation: 351
I am reading a file of integers. I want to save integers from each line to a new array. 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
Upvotes: 2
Views: 47261
Reputation: 11
#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.
Upvotes: 0
Reputation: 13
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
.
Upvotes: 0
Reputation: 399743
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.
Upvotes: 0
Reputation: 13257
#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;
}
Upvotes: 3
Reputation: 111
If you use reading char by char then recognizing whitespace with '32' and 'enter' by '13' and/or '10'
Upvotes: -1
Reputation: 272467
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.
Upvotes: 9