I would like to read a file called "input" with a lot of lines and 10 columns into an array using C. I wrote the following code:
FILE *file;
file=fopen("input","r");
i=0;
while ( fgetc(file) != EOF )
{
fscanf(file,"%e\t%e",&x[i],&y[i]);
i++;
}
The problem that I am ecoutering is that the first element of the file is not read. It is read however when the file contains an initial indent.
Could you help me?
Thank you in advance.
fgetc() reads a character and returns it and increments the file pointer. next when you call fscanf(), the first character won't be seen as its already past first character. If you want, only use fscanf() and check for EOF to detect end of file.
Related
I'm still a novice in C as I just started out. Here is a part of my function to open the file and then save the file lines into variables. I did while to loop until the end of file so I can get the last line, however it did not go as expected. So, I was wondering how can I get just the last line from a text file? Thank you.
tfptr = fopen("trans.txt", "r");
while (!feof(tfptr)){
fscanf(tfptr, "%u:%u:%.2f\n", &combo_trans, &ala_trans, &grand_total);
}
fclose(tfptr);
sample text file:
0:1:7.98
1:1:20.97
2:1:35.96
2:2:44.95
2:2:44.95
3:2:55.94
In your fscanf(tfptr, "%u:%u:%.2f\n", &combo_trans, &ala_trans, &grand_total);, the %.2f will cause problem.
You can't specify the precision for floating-point numbers in scanf() unlike in the case of printf(). See this answer.
So, instead of %.2f in the scanf format string, use just %f.
Since you just need the last line, you could just read the file line by line with fgets() and keep the last line.
while( fgets(str, sizeof(str), tfptr)!=NULL );
printf("\nLast line: %s", str);
fgets() will return NULL when the file is over (or if some error occurred while reading).
The lines in the input file are read one by one and when there are no more lines to read, str (a character array of suitable size) will have the line that was read last.
You could then parse the string in str with sscanf() like
sscanf(str, "%u:%u:%f", &combo_trans, &ala_trans, &grand_total);
Also, you should be checking the return value of fopen() to see if the file was really opened. fopen() will return NULL if some error occurred.
if( (tfptr = fopen("trans.txt", "r"))==NULL )
{
perrror("Error");
}
What did go wrong? Did you get another line?
Don't use "&" as you don't want to save a pointer. That can be the reason of failure.
I try to get input from a text file. First line of the text only contains a number, then others related with it like that;
4
ssss
sss
ss
s
I used fgets function for getting these lines from file, but I want to use "4" and the other lines in different functions.
I was getting both these lines with fgets like that;
char inp[150];
int i;
FILE *fp;
while(1) {
if(fgets(inp, 150, fp) == NULL) break;
printf("%s",inp);
i++;
}
I used printf for only see that this code getting all lines or not. It is getting all lines same with input, but when I try to print first line of the input "inp[0]", I expect to print "4", but it prints "s" again.
Therefore, I can't use or get the number which is in the first line. How can I print or use first line independently from others.
By the way, the number and the other lines ,which are related with it, can change with another inputs.
Pass the file pointer to the functions, and have them attempt to read the lines.
That's a basic parser for you.
Don't forget to:
Do error handling, and properly indicate if a read failed.
Reset the file pointer position in case of failure.
Store the result of fgetpos at the beginning and restore it with fsetpos
The problem with your code is that fgets(inp, 150, fp) reads until newline, 149 characters read or EOF.
So each timefgets(inp, 150, fp) you store new values in inp. And last value is s.
Try to use fgetc and store character by character in inp.
I ran into a problem today. I can't find a way to check if a line in a file is over and the words are read from the next one already. I read word by word from the file using fscanf, then process the word as I need to and print it out into another file but there is a problem.
for example my data file is:
Hello, how are you
doing?
and the result file shows:
Hello, how are you doing?
but i need the words to be in the same lines from which I took them. Please keep in mind that I need those words one by one, that is why I don't use getline()
here is my code of how I read words from the file:
while( fscanf(file, "%s", A) != EOF )
{
check(A, B, &a); // I edit the words and put them in B string
// which is printed to the write file
}
Thank you for any tips!
Read the line into a string with getline() or fgets(), then use sscanf to get the words out of this string.
You can use a simple logic instead, like matching strings like . or ? which generally ends lines.
You need to check for end of line by adding check.
As the end-of-line is represented by the newline character, which is '\n'. so in while loop instead of copying entire thing do it line by line with the help of check for '\n'
I'm trying for hours to find the answer for this question i've got in university. I tried running this with writing a file with two lines of :
hello
world
and it reads the file perfectly, So i cant find the answer. I would appreciate your help !
A student wrote the next function for reading a text file and printing it exactly as it is.
void ReadFile(FILE *fIn)
{
char nextLine[MAX_LINE_LENGTH];
while(!feof(fIn))
{
fscanf(fIn,"%s",nextLine);
printf("%s\n",nextLine);
}
}
What are the two errors in this function?
You can assume that each line in the file is not longer than MAX_LINE_LENGTH characters, and that it is a text file that contains only alphabet characters, and that each line is terminated by '\n'.
Thanks.
It discards white space. Try adding multiple spaces and tabs.
It may evaluate a stream more than once, and If there is a read error, the loop never terminates.
See: Why is “while ( !feof (file) )” always wrong?
Reading strings via scanf is dangerous. There is no bounds checking. You may read past you MAX_LINE_LENGTH.(and boom! Segfault)
The main error is that fsacnf( fIn, "%s", nextLine ) doesn't scan a complete line.
From man page:
s
Matches a sequence of non-white-space characters; the next pointer must be a pointer to character array that is long enough to hold the input sequence and the terminating null byte ('\0'), which is added automatically. The input string stops at white space or at the maximum field width, whichever occurs first.
Thus if you have a line "a b" the first fscanf() will scan just "a" and the second one "b" and both are printed in two different lines. You can use fgets() to read a whole line.
The second one is maybe that it's stated "each line in the file is not longer than MAX_LINE_LENGTH characters" but nextLine can contain atmost MAX_LINE_LENGTH-1 characters (+ '\0'). That problem becomes even more important if you replace fscanf() by fgets() because than nextLine must have also capacity to store '\n' or '\r\n' (depending on the platform you're on)
A correct way of doing that is:
void ReadFile(FILE *fIn)
{
char nextLine[MAX_LINE_LENGTH];
while(fgets(nextLine, MAX_LINE_LENGTH, fIn)) {
printf("%s", nextLine);
}
}
As some have posted using feof to control a loop is not a good idea nor using fscanf to read lines.
Hello i have simply function to read from file
while(fscanf(fp," %255[a-zA-Z]",test) == 1)
{
puste = 1;
push(&drzewo,test);
}
It should read only words which contains only alphabetic characters and that works great. When I have for example a single number in my file my while loop quits; how should I change it?
Of course it stops, since the fscanf() call will fail to do the conversion you're requiring, and thus return 0. What would you expect it to do?
It's often better to read whole lines using fgets(), and then parse them "manually", that way it's easy to just do nothing and read another line if the desired data is not found.