473,549 Members | 2,627 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

reading from a text file

I'm trying to read from an input text file and print it out. I can do
this by reading each character, but I want to implement it in a more
efficient way. So I thought my program should read one line at a time
and print it out. How can I do this? I wrote the code below but it's
not correct since the fscanf reads one word (terminating in whitespace
or newline) at a time, instead of reading the whole line.

#include <stdio.h>
void main(void)
{
char str[120];

FILE *fp = fopen("test.txt ", "r");

while (!feof(fp))
{
fscanf(fp, "%s\n", str);
printf("%s", str);
}
}

So I get an output like "Thisisatest.It isnotworking.", when the input
file contains:
This is a test.
It is not working.

Any suggestion is appreciated. Thanks.

Nov 15 '05 #1
40 4476
googler wrote:
I'm trying to read from an input text file and print it out. I can do
this by reading each character, but I want to implement it in a more
efficient way. So I thought my program should read one line at a time
and print it out. How can I do this? I wrote the code below but it's
not correct since the fscanf reads one word (terminating in whitespace
or newline) at a time, instead of reading the whole line.
<snip> Any suggestion is appreciated. Thanks.


fgets.

S.
Nov 15 '05 #2
Skarmander wrote:
googler wrote:
I'm trying to read from an input text file and print it out. I can do
this by reading each character, but I want to implement it in a more
efficient way. So I thought my program should read one line at a time
and print it out. How can I do this? I wrote the code below but it's
not correct since the fscanf reads one word (terminating in whitespace
or newline) at a time, instead of reading the whole line.

<snip>
Any suggestion is appreciated. Thanks.


fgets.

S.


Sorry, I should have used fgets.. my bad.

One more question. My code looks like:
while (!feof(fp))
{
fgets(str, 120, fp);
printf("%s", str);
}

This prints the last line twice. I don't understand why. When it prints
the last line for the first time, it should have known that the end of
the file has been reached, so the next condition check for the while
loop should have failed. Why is it still entering the while loop and
printing the last line again?

Thanks.

Nov 15 '05 #3
Don't use feof. You can always use fgets to check if it gets to the end
of the file.

for example,
while( fgets(str, 120,fp) )
{
printfr("%s", str);
}

cheers

Nov 15 '05 #4
Reading a line and a character are not much different in terms of
efficiency because a caching is already done by file reader function.
Meaning it reads some blocks (much more than you need) of file at one
time and stores it on the memory. I think you must use the appropriate
one according to your need. If you just want to print the file on the
screen the two would not make much difference but fgets would be a
little better. And in processing the sum of "a little"s are big.

Nov 15 '05 #5
Or actually, I should've done some explanation that, during your last
double-printing, fgets returned NULL whilst the "str" memory stayed the
same in terms of the content.

the workaround to your problem whilst keeping the feof would be as
follows:
while ( !feof(fp) )
....
if( fgets(...) )
printf....

Nov 15 '05 #6
googler said:
I'm trying to read from an input text file and print it out. I can do
this by reading each character, but I want to implement it in a more
efficient way. So I thought my program should read one line at a time
and print it out. How can I do this? I wrote the code below but it's
not correct since the fscanf reads one word (terminating in whitespace
or newline) at a time, instead of reading the whole line.
Others have already answered your question, but nobody appears to have
pointed out yet that...

#include <stdio.h>
void main(void)


....in C, main returns int, not void. This is a common error, and those who
commit it often find it hard to believe that it's wrong. Nevertheless, no C
compiler is required to accept a main function that returns void unless it
specifically documents that acceptance - which few, if any, do.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Nov 15 '05 #7
In article <11************ **********@g14g 2000cwa.googleg roups.com>
googler <pi********@yah oo.com> wrote:
One more question. [The following code fragment, slightly edited for space]
while (!feof(fp)) {
fgets(str, 120, fp);
printf("%s", str);
}
... prints the last line twice. I don't understand why. When it prints
the last line for the first time, it should have known that the end of
the file has been reached,


What makes you believe that? Remember that fgets() is (loosely)
defined as:

int c;
while ((c = getc(fp)) != EOF && c != '\n') {
line[i++] = c;
if (c == '\n')
break;
}
line[i] = '\0';

(of course fgets() avoids overrunning your buffer, so it is a little
more complicated than that, but assume for the moment that no input
lines will be overlong).

Suppose the stdio "FILE *fp" is connected to a human being (at the
keyboard, or a terminal, or behind a network connection via telnet
or ssh or whatever), who has some way of signalling "end of file"
while still remaining connected (on many OSes this is done by
entering ^Z or ^D or @EOF or some similar character or string as
the only input on a line). The human types:

abc[enter]

so the first fgets() reads "abc\n". The fgets() call returns.
What should feof(fp) be?

The human *might* be *about* to press ^D or ^Z or type @EOF or
whatever it is that will signal EOF. Should feof(fp) wait until
he does so? What should it do if, instead, he types "def" and
presses ENTER?

You are effectively expecting the feof() predicate to predict the
future. There is no way for it to do that. It *could*, of course,
try to read input from the file -- in effect, waiting for the human
to signal EOF or enter "def\n". But it does not do that. Predicting
the future is too difficult. C is a simple language. It is much
easier to "predict" the past ... so that is what feof() does!
Instead of telling you "a future attempt to read is not going to
work because EOF is coming up", it tells you "a previous attempt
to read that failed, failed because EOF came up."

Suppose, now, that instead of a human, the stdio FILE *fp is
connected to a file on a floppy disk (or CD-ROM or DVD or whatever).
Suppose further that the floppy has been corrupted (someone used
a magnet to hold it up on the fridge, or scratched the CD-ROM, or
whatever). Your program/OS knows that the file should be 271483
bytes long, but partway in, the media turns out to be unreadable.
The fgetc() function -- or its getc() equivalent -- will return
EOF, indicating that it is unable to continue reading.

What should feof(fp) be? The file size is known (271483 bytes)
but you have at this point successfully read only 65536 bytes.
Should feof(fp) return nonzero (true)? You have not reached the
end of the file!

As before, feof() does not try to predict the future; instead, it
"predicts" the past. It tells you whether the getc() that returned
EOF did so because of end-of-file. In this case, it is *not* the
end of the file -- so feof(fp) is 0 (i.e., false). The other
predicate, ferror(fp), will be nonzero (i.e., true). It is
"predicting " the past, and telling you that the getc() failed due
to error. (Of course, the ability to distinguish between "normal
end of file" and "error reading data" is O/S and sometimes filesystem
or device specific, but it is fairly common.)

Because feof() only tells you about *previous* failures, and --
worse -- only tells you about EOF and not about errors, any loop
of the form:

while (!feof(fp))

is virtually *guaranteed* to be wrong. If you ever see this in
C code, be very suspicious.

As for why the last line prints twice, well, that one is a FAQ. :-)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 15 '05 #8
googler wrote:

I'm trying to read from an input text file and print it out. I can do
this by reading each character, but I want to implement it in a more
efficient way. So I thought my program should read one line at a time
and print it out. How can I do this? I wrote the code below but it's
not correct since the fscanf reads one word (terminating in whitespace
or newline) at a time, instead of reading the whole line.

#include <stdio.h>
void main(void)
{
char str[120];

FILE *fp = fopen("test.txt ", "r");

while (!feof(fp))
{
fscanf(fp, "%s\n", str);
printf("%s", str);
}
}

So I get an output like "Thisisatest.It isnotworking.", when the input
file contains:
This is a test.
It is not working.

Any suggestion is appreciated. Thanks.


/* BEGIN new.c */

#include <stdio.h>
#include <stdlib.h>

#define SOURCE "test.txt"
#define LINE_LEN 119
#define str(s) # s
#define xstr(s) str(s)

int main(void)
{
int rc;
FILE *fd;
char line[LINE_LEN + 1];

fd = fopen(SOURCE, "r");
if (fd == NULL) {
fprintf(stderr,
"\nfopen() problem with \"%s\"\n", SOURCE);
exit(EXIT_FAILU RE);
}
do {
rc = fscanf(fd, "%" xstr(LINE_LEN) "[^\n]%*[^\n]", line);
if (!feof(fd)) {
getc(fd);
}
if (rc == 0) {
*line = '\0';
++rc;
}
printf("%s\n", line);
} while (rc == 1);
fclose(fd);
return 0;
}

/* END new.c */
--
pete
Nov 15 '05 #9
pete wrote:

googler wrote:

I'm trying to read from an input text file and print it out.
I can do
this by reading each character, but I want to implement it in a more
efficient way. So I thought my program should read one line at a
time
and print it out. How can I do this? I wrote the code below but it's
not correct since the fscanf reads one word
(terminating in whitespace
or newline) at a time, instead of reading the whole line.

#include <stdio.h>
void main(void)
{
char str[120];

FILE *fp = fopen("test.txt ", "r");

while (!feof(fp))
{
fscanf(fp, "%s\n", str);
printf("%s", str);
}
}

So I get an output like "Thisisatest.It isnotworking.",
when the input
file contains:
This is a test.
It is not working.

Any suggestion is appreciated. Thanks.


/* BEGIN new.c */


new.c outputs the last line double.
I'm working on it.

--
pete
Nov 15 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
12710
by: Suresh Kumaran | last post by:
Hi All, Does anybody know the sytax in VB.NET to write the contents of a multiline text box to a text file? Appreciate help. Suresh
1
7038
by: fabrice | last post by:
Hello, I've got trouble reading a text file (event viewer dump) by using the getline() function... After 200 - 300 lines that are read correctly, it suddenly stops reading the rest of the file... Thank you to all of you who can help me with this one...
19
10280
by: Lionel B | last post by:
Greetings, I need to read (unformatted text) from stdin up to EOF into a char buffer; of course I cannot allocate my buffer until I know how much text is available, and I do not know how much text is available until I have read it... which seems to imply that multiple reads of the input stream will be inevitable. Now I can correctly...
0
1735
by: Eric Lilja | last post by:
Hello, I have a text file that contains a number of entries describing a recipe. Each entry consists of a number of strings. Here's an example file with only one entry (recipe): Name=Maple Quill Process=Interim Level=10 Technique=Fletching Knowledge=Woodworking Device=Sawhorse Primary components=Refined Maple
1
6742
by: Magnus | last post by:
allrite folks, got some questions here... 1) LAY-OUT OF REPORTS How is it possible to fundamentaly change the lay-out/form of a report in access? I dont really know it that "difficult", but listen up; Reports, the way I look at them, all present data downwards, in this way; TITLE data
50
4895
by: Michael Mair | last post by:
Cheerio, I would appreciate opinions on the following: Given the task to read a _complete_ text file into a string: What is the "best" way to do it? Handling the buffer is not the problem -- the character input is a different matter, at least if I want to remain within the bounds of the standard library.
2
2469
by: Sabin Finateanu | last post by:
Hi I'm having problem reading a file from my program and I think it's from a procedure I'm using but I don't see where I'm going wrong. Here is the code: public bool AllowUsage() { OperatingSystem os = Environment.OSVersion; AppDomain ad = Thread.GetDomain();
4
3277
by: dale zhang | last post by:
Hi, I am trying to save and read an image from MS Access DB based on the following article: http://www.vbdotnetheaven.com/Code/Sept2003/2175.asp Right now, I saved images without any errors. After reading the ole object from db, I saved it to C: as file1.bmp and displayed on the web. But it can not be displayed. After I manually sent...
4
12776
by: Amit Maheshwari | last post by:
I need to read text file having data either comma seperated or tab seperated or any custom seperator and convert into a DataSet in C# . I tried Microsoft Text Driver and Microsoft.Jet.OLEDB.4.0 to read text file but could not get the data in correct format. All columns are not coming in dataset and rows are messing up. Suggestions...
3
2812
by: The Cool Giraffe | last post by:
Regarding the following code i have a problem. void read () { fstream file; ios::open_mode opMode = ios::in; file.open ("some.txt", opMode); char *ch = new char; vector <charv; while (!file.eof ()) { do {
0
7451
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7720
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7959
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7473
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6044
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5369
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5088
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3501
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3483
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.