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'
Related
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'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.
I pretty much have the whole code figured it, the problem is that the file has names, some names include the middle name some don't. each name in the file is in a new line
Lincoln, Abraham
Obama, Barak Hussien
Doe, John
now my problem with this is I originally had two arrays reading in each name with fscanf but it reads Hussien as a new line? So then I try to do three arrays for the middle name as well, but when it read in the file it displayed the output as.
Lincoln, Abraham Obama
Barak Hussien Doe
John
while ( fscanf( input,"%s %s", &last[i],&first[i] ) != EOF )
{ i++; }
what am I doing wrong? I would like to scan the whole line in but in another part of the program I must have first and last name seperated as "user ids" will be created ex. a_lincoln, etc.
Use "%[^,], %[^\r\n]" as the format string in your fscanf. It ignores the colon for the last name and read the remaining characters in the same line for the first name.
do this
char *last[30];
char *first[30];
while ( fscanf( input,"%s %s", last[i],first[i] ) != EOF )
In the format string for fscanf or scanf or sscanf, each instance of whitespace causes the function to read and discard any whitespace that appears in the input at that place, including newline characters. So fscanf isn't going to read things line-by-line.
You need to call a different function to read a line into a string. Then call sscanf to read the string, first the part up to a comma, and then the part after a comma.
Read a line from file using
while ( fscanf( input,"%[^\n]s", line) != EOF )
"line could be character array or char pointer"
now you have complete line from the file
for each line make use of strtok() function to seperate tokens
using token count you will get to know if midle name is present or not.
Here's my code:
FILE* fp,*check;
fp=fopen("file.txt","r");
check=fp;
char polyStr[10];
while(fgetc(check)!='\n')
{
fscanf(fp,"%s",polyStr);
puts(polyStr);
check=fp;
}
while(fgetc(check)!=EOF)
{
fscanf(fp,"%s",polyStr);
puts(polyStr);
check=fp;
}
Now if my file.txt is:
3,3, 4,4, 5,5
4,1, 5,5, 12,2
Now output is:
,3,
4,4,
5,5,
,1,
5,5,
12,2,
Now why is the first character of both the lines not getting read?
Your fgetc call is eating the character.
You should read entire lines with fgets and then parse them with the strtol family. You should never use any of the *scanf functions.
Let's talk about the format of the input data first. Your list would seem to be better formatted if you only had <coef>,<exp> without the trailing comma. In this way, you would have a nice pattern with which to match. So you could do something like:
fscanf(filep, "%d,%d", &coef, &exp)
to get the values. You should check the return value from fscanf to be sure that you are reading 2 fields. So if the format of a line was a set of the following '<coef>,<exp><white-space>' (where white-space is either one blank or one newline, then you would be able to do the following:
do {
fscanf(filep, "%d,%d", &coef, &exp);
} while (fgetc(filep) != '\n');
This code allows you to get the pairs until you eat the end of line. The while conditional will eat either the blank or the newline. You can wrap this in another loop for processing several lines.
Note that I have NOT tested this code, but the gist of it should be clear. Comment if you have any more questions.