473,396 Members | 1,846 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

question abt fscanf

Hi All,

here is one code:
int main() {
FILE*fp;
unsigned long a;
fp = fopen("my_file.txt","w+");
a = 24;
fprintf(fp,"%ld",a);
while(fscanf(fp,"%ld",&a) == 1) {
printf("%ld",a);
count++;
}
printf("count = %ld",count);
return(0);
}

I belive tht data in file is stored as ascii character constants i.e
'2' & '4'.
When data is retrived back with fscanf,does it read character by
character i.e 1 char in one iteration or it reads 2 characters at once
due to "%ld"?
well does %d,%c,%ld make any difference in retriving data with fscanf
or does fscanf read data char by char?
Do these format specifiers perform an ascii to binary conversion
before storing data in dest variable?
pls help.
Thanks
-Siliconwafer

Nov 15 '05 #1
1 2181
In article <11**********************@f14g2000cwb.googlegroups .com>
siliconwafer <sp*********@yahoo.com> wrote:
here is one code:
int main() {
FILE*fp;
unsigned long a;
fp = fopen("my_file.txt","w+");
a = 24;
fprintf(fp,"%ld",a);
This code is already broken: what if fopen() returns null?
while(fscanf(fp,"%ld",&a) == 1) {
As of this line, this code is now *severely* broken. Even if
the fopen() succeeds, the first operation done (a printf) puts
the file in "write mode". Standard C makes requirements on
the programmer before taking a "write mode" file (opened for
r+, w+, or a+ but put into write mode) and using it for "read
mode". In general, you should do a file-seeking operation
first, such as:

result = fseek(fp, 0L, SEEK_CUR);

At least this code tests the result of the scanf() call, though! :-)
printf("%ld",a);
count++;
}
printf("count = %ld",count);
return(0);
}

I belive tht data in file is stored as ascii character constants i.e
'2' & '4'.
Maybe; maybe not. Since the argument to fopen() was "w+", the file
is emptied of any previous contents and is manipulated as a text
file (rather than a binary file). Whether the text is ASCII depends
on other factors -- an IBM mainframe, for instance, would typically
use EBCDIC instead.
When data is retrived back with fscanf,does it read character by
character i.e 1 char in one iteration or it reads 2 characters at once
due to "%ld"?
This question reveals some basic misunderstandings.

All file I/O is defined in terms of fgetc() and fputc(), i.e., one
character at a time. However, the scanf() family of functions
(scanf, fscanf, sscanf, and in C99 the vscanf etc variants) use
what I like to call a "scanf engine" to read and interpret input.
The scanf engine obeys the directives given in the format string.
Format directives include percent-prefixed conversions, like %c
and %d, and also literal characters and whitespace.

The %ld directive consists of three parts: the '%' sign that
introduces a conversion, the 'l' modifier, and the 'd' conversion
directive. The 'l' modifier tells the scanf engine to read
and convert a "long int" rather than a plain int, in this case.

The conversion itself begins by reading and consuming as much
white space as possible, with the logical equivalent of:

int c;
do {
c = fgetc(fp);
} while (isspace(c));

Note that this skips leading blanks, tabs, newlines, backspaces,
form-feeds, and vertical-tabs. It will read straight through six
million blank lines if necessary, all without any sort of warning
or hint that it is doing so.

Having finished the above loop (or some other equivalent code),
the "%d" directive continues to read and consume characters until
it gets a non-sign and non-digit character:

if (c == '-' || c == '+') {
... remember the sign as neeeded ...
c = fgetc(fp);
}
while (isdigit(c)) {
... accumulate the value to convert ...
c = fgetc(fp);
}

The loop here terminates only when c is not a digit; at this point,
either c is a non-digit character, or c==EOF. If c is not equal to
EOF, the scanf engine has to put it back into the stream, as if
via ungetc() but without disturbing the ability for the user to
do his own ungetc() call:

if (c != EOF)
internal_ungetc(c, fp);

Except for this "special version of ungetc", you can write fscanf()
yourself in portable ANSI C. The main reasons to use the implementor's
version (such as the one I provided for the various BSDs) is that
(a) the implementor already did the work, and (b) he may have taken
advantage of the implementation to make the code more efficient
than straight fgetc() calls.

Finally, %d (or %ld in this case) will, if assignment was not
suppressed via "%*", store the result of a conversion -- done mostly
as if via strtol(), but with undefined behavior if the result does
not fit -- through the pointer that the caller must have supplied
as the appropriate variable argument:

*(va_arg(ap, long *)) = strtol(accumulated_value, NULL, 10);
well does %d,%c,%ld make any difference in retriving data with fscanf
or does fscanf read data char by char?
This question seems to imply that these are contradictory options.
They are not. The conversions make a great deal of difference,
but fscanf must always act "as if" it read the data one "char" at
a time. However, the "%c" conversion *does not* skip leading
whitespace:

if (conversion == 'c' || conversion == '[')
c = fgetc(fp); /* do not skip white space */
else {
/* do skip leading whitespace */
do {
c = fgetc(fp);
} while (isspace(c));
}
if (c == EOF)
... handle input failure ...
/* now c is the first character of the field */
switch (conversion) {
... handle %c, %d, %o, %s, %[, etc conversions ...
}
Do these format specifiers perform an ascii to binary conversion
before storing data in dest variable?


Again, ASCII is not required, but "%d" conversions behave similarly
to atoi(), atol(), strtol(), and so on.
--
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 #2

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

Similar topics

3
by: Fallon | last post by:
If someone could help it would be greatly appreciated. I am trying to write a simple program to read in elements from an input file formatted as follows: 3 4 81 5 6
4
by: Cal Lidderdale | last post by:
My input line is i1,i2,i3,i4,i5,i6,i7,i8^,...i596,597, ... 14101,14102...NL/CR very long line of data - I only want the first 8 items and the delimiter between 8 & 9 is a carrot "^". The line...
5
by: No Such Luck | last post by:
Hi All: I have a loop in which I scan an entire file for a particular string ("Error:"). However, I don't know the specifics of testing for the EOF. while (1) /* This should be while (!EOF) or...
2
by: Gary Baydo | last post by:
The following program illustrates a question I have about fscanf() behavior: #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { FILE *testfile; char s1 =...
2
by: yezi | last post by:
Hi, ALl: The following code is to canculate 2 vector distance. Suppose the vectore is stored in some txt file like -1 0.34 0 0.045 1 0.98 1 0.01
7
by: ehui928 | last post by:
I use the following program to read some strings from an inupt file, and print them on the standard output. But the last string in the input file always printed twice, what is the reason and how...
6
by: haloman | last post by:
Why does: char *myString = (char *) malloc(WORDLIMIT*sizeof(char)); fscanf(openFile, "%s", myString) != EOF; work yet char *myString = (char *) malloc(WORDLIMIT*sizeof(char));...
10
by: Roman Zeilinger | last post by:
Hi I have a beginner question concerning fscanf. First I had a text file which just contained some hex numbers: 0C100012 0C100012 ....
8
by: Fred | last post by:
I've got following program encapsuled fscanf, however, it doesn't work. I'm sure that the content format in "a.txt" is OK, the content would be correctly read if using fscanf directly, what's...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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...
0
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,...
0
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

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.