473,763 Members | 8,423 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2213
In article <11************ **********@f14g 2000cwb.googleg roups.com>
siliconwafer <sp*********@ya hoo.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 misunderstandin gs.

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(accumula ted_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
7243
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
2348
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 can end at the 100th item or the 40,000th item. My code is: char data, mynull;
5
4779
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 something */ { fscanf (file, "%s", string); if (!strcmp (string, "Error:")); {
2
1545
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 = "01234567890123456789";
2
1875
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
3981
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 can I make the last string be printed only once? Anyone give me some suggestions? input.txt: abc def ghi jk lm
6
5512
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)); fscanf(openFile, "%s", &myString) != EOF; doesn't (crashes, doesn't result in a compiler error)? I thought the
10
4461
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
2777
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 wrong with my program? Thanks for help! int vsscanf( FILE* fp, const char *fmt, ... ) { va_list arglist; va_start( arglist, fmt );
0
9387
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10148
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10002
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9938
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
8822
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7368
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6643
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5270
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3917
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.