reading from a text file in C Programming [duplicate] - c

This question already has answers here:
Reading a C file, read an extra line, why?
(6 answers)
Closed 8 years ago.
I am trying to write a C program that is able to read data (strings) from a text file and swap each content in terms of bytes. I have already implemented the code and everything works just fine, and and I am able to read all the contents of the specified text file, but the problem is that the program is printing the last word from the text file twice and I do not know why? Any help will be helpful ! This is the code I have:
while( !feof(ptr_file))
{
//to read in group of words (sentences) if
//needed !.
fscanf(ptr_file, "%s", userName);
//time to swap letters of the word coming from the text file.
swap_a_word(userName, 0, 4);
swap_a_word(userName, 1, 2);
//new space.
printf("\n");
//display the word after swapping to the screen for the user.
printf("%s", userName);
}
The program must not print extra data. I do not know, but when the program reaches the end of the file, it prints the last data of the text file twice. Please any hints will be helpful !.
Thanks !

The problem is the while loop condition
while(!feof(ptr_file))
Note that EOF is preceded by a newline '\n'. fscanf returns the value EOF when the end of file is reached. However, this does not set the end-of-file indicator on the stream and as a result the loop is entered one extra time. You should check the return value of fscanf instead to find number of items successfully matched and assigned.

Related

Looping fscanf causing additional loops (C language)

I am facing problems looping a fscanf. As in the code below (focus on the part where the while loop starts), I am looping the fscanf until it reached EOF. As you can see from the 2nd part below, the .txt file to fscanf from has only 6 strings,so the fscanf should only loop 6 times and then it reaches EOF. However, as you can see from the program output (2nd part belowe), the fscanf is looped 7 times. Since my program displays the missilenames in reverse order, I assume the while loop looped 1 additional time at the end, resulting at the blank line output on the first line of 3rd picture.
Can someone tell me how to fix this problem pls?
C CODE
while(fscanf(readmissiles,"\n %s \n",missilename)!=EOF)
{
missilename=malloc(20*sizeof(char));
insertvalue(LL,missilename);
missilenum++;
}
TEXT FILE TO FSCANF FROM
single
splash
single
V-Line
h-line
Single
OUTPUT/DISPLAY
/there is a blank line displayed before the Single/
Single
h-line
V-Line
single
splash
single
7
fscanf returns the number of elements scanned or EOF in case of error or end of file is reached before it could match anything. On the last loop fscanf returns 0 - it did not scan the element but it scanned \n, so it returns 0. Do:
while(fscanf(readmissiles, "%s", missilename) == 1)
Loop until there is one element scanned.

fgets() and text files [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
My book mentions that fgets will read until it meets the (n-1)th character or a character of a new line. By character of new line do we only mean Enter (\n)? I am asking this because what I did was to create a text file on which I started typing in some nonsense, surpassing the character limit of each line meaning that I used more than one lines. After that I used fgets and what I expected was it to read only the characters in the first line of the text file but what it did was read all of them.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char box[5000];
FILE *fp;
fp = fopen("test.txt", "r");
fgets(box, 5000, fp);
puts(box);
}
Test.txt (The text is random that's why it's silly) (285 characters):
kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk25kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkggggggggggiiiiiiiiiiiiiiiiiiii
So the result I expected was for it to print only part of the text and actually as many characters as the limit that is set for one line, minus one, (which I think is something above 250). But instead of that, it prints all of them. Note: The same thing happens even I type even more characters in the file.
You seem to be assuming that there's an upper limit, perhaps 255 characters, on the length of a line in a text file. C imposes no such limit, except indirectly by using int as the size argument to fgets.
Your program defines a 5000-character array and calls fgets with a length argument of 5000. That means it can read a single line of up to 5000 characters (or close to that; I'm ignoring a couple of off-by-one issues for the '\n' and '\0' characters). The input line in your question is only 285 characters long, so your program will easily read it as a single line.
You can try changing the length of your array to see what happens when an input line is too long to fit:
char box[255];
...
fgets(box, sizeof box, fp);
Note that using sizeof box rather than repeating the number means the call won't get out of sync with the array size.
It only stops at the newline character \n or at n-1 characters. There is no newline character other than \n.
As you set the limit for your buffer and the amount fgets can read to 5000, it can easily read all the characters in your file and print them.
There is no line length limit in ISO C (ISO/IEC 9899), whether one is imposed by your book or not. Your book is probably outdated.

fgets to include text after newline [duplicate]

This question already has answers here:
Correct way to read a text file into a buffer in C? [duplicate]
(8 answers)
Closed 7 years ago.
I want to make an array of characters and store the whole input in it(even if the input contains "\n" at some point. When i use:
char vhod[50];
fgets(vhod, sizeof(vhod), stdin);
it stores the input UNTIL the first newline. How to get the whole text in this array(including the text after the new line).
Example:
if my text is:
Hello I need new keyboard.
This is not good.
my array will only contain "Hello I need new keyboard.". I want to be able to read everything till the end of input a < input-1
I cannot use FILE open/close/read functions since it is input from keyboard.
While fgets() is designed to read up to a '\n' character or the specified number of bytes, you can use fread()1 instead, like this
size_t count = fread(vhod, 1, sizeof(vhod), stdin);
and count will contain the number of items read, which in this case is the same as the number of bytes since you are providing size 1 i.e. sizeof(char).
Note however that you must be very careful to add a terminating '\0' if you are going to use any function that assumes a terminating '\0'.
1Read the manual for more information.

How do I check if the line is over?

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/O in C Errors

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.

Resources