473,747 Members | 2,556 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

beginner fscanf question

Hi

I have a beginner question concerning fscanf.
First I had a text file which just contained some
hex numbers:

0C100012
0C100012
....

It was easy to read this values into an integer variable:
FILE *fp = fopen("test.dat ","r");
int mem_word = 0;
while (fscanf(fp,"%x" , &mem_word) != EOF)
....

Now, I have the following format where my hex number
is splitted by spaces. So I wonder if there is
an easy way to parse such a line and not doing
a lot of space removing etc.

0C 10 00 12 // 00000000
0C 10 00 12 // 00000000
....

Thanks for helpful comments.
Aug 15 '07 #1
10 4458
Roman Zeilinger wrote:
Now, I have the following format where my hex number
is splitted by spaces. So I wonder if there is
an easy way to parse such a line and not doing
a lot of space removing etc.
I don't think so. But it's trivial to remove the spaces and then use
sscanf().
0C 10 00 12 // 00000000
0C 10 00 12 // 00000000
Or you could write your own simple parser
Aug 15 '07 #2
Roman Zeilinger <Ro************ *@yahoo.dewrote :
Hi
I have a beginner question concerning fscanf.
First I had a text file which just contained some
hex numbers:
0C100012
0C100012
...
It was easy to read this values into an integer variable:
FILE *fp = fopen("test.dat ","r");
int mem_word = 0;
while (fscanf(fp,"%x" , &mem_word) != EOF)
...
Now, I have the following format where my hex number
is splitted by spaces. So I wonder if there is
an easy way to parse such a line and not doing
a lot of space removing etc.
0C 10 00 12 // 00000000
0C 10 00 12 // 00000000
If there's always " // 00000000" at the end of the line and
never anything else (except trailing white space) it's rela-
tively simple:

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

int main( void ) {
FILE *fp = fopen( "sh.dat", "r" );
unsigned int d[ 4 ];
unsigned int x;

if ( fp == NULL )
return EXIT_FAILURE;

while ( fscanf( fp, "%x%x%x%x // 00000000",
d, d + 1, d + 2, d + 3 ) == 4 ) {
x = ( ( ( ( ( d[ 0 ] << 8 ) + d[ 1 ] ) << 8 )
+ d[ 2 ] ) << 8 ) + d[ 3 ];
printf( "x = %x\n", x );
}

return 0;
}

but if that's not the case then you will need to do a bit more of
work in that while loop:

while ( fscanf( fp, "%x%x%x%x", d, d + 1, d + 2, d + 3 ) == 4 ) {
x = ( ( ( ( ( d[ 0 ] << 8 ) + d[ 1 ] ) << 8 )
+ d[ 2 ] ) << 8 ) + d[ 3 ];
printf( "x = %x\n", x );
while ( ( c = fgetc( fp ) ) != '\n' && c != EOF )
/* empty */ ;
}

You also will need to add a definition of 'c' (as an int, not a
char!).

You could use something simpler if you can be sure that there will
be never more than 12 characters following your quadruplet of hex
numbers (again except trailing white space characters):

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

int main( void ) {
FILE *fp = fopen( "sh.dat", "r" );
unsigned int d[ 4 ];
unsigned int x;
char buffer[ 13 ];

if ( fp == NULL )
return EXIT_FAILURE;

while ( fscanf( fp, "%x%x%x%x%1 2[^\n]",
d, d + 1, d + 2, d + 3, buffer ) == 5 ) {
x = ( ( ( ( ( d[ 0 ] << 8 ) + d[ 1 ] ) << 8 )
+ d[ 2 ] ) << 8 ) + d[ 3 ];
printf( "x = %x\n", x );
}

return 0;
}
Regards, Jens
--
\ Jens Thoms Toerring ___ jt@toerring.de
\______________ ____________ http://toerring.de
Aug 15 '07 #3
You could use something simpler if you can be sure that there will
be never more than 12 characters following your quadruplet of hex
numbers (again except trailing white space characters):

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

int main( void ) {
FILE *fp = fopen( "sh.dat", "r" );
unsigned int d[ 4 ];
unsigned int x;
char buffer[ 13 ];

if ( fp == NULL )
return EXIT_FAILURE;

while ( fscanf( fp, "%x%x%x%x%1 2[^\n]",
d, d + 1, d + 2, d + 3, buffer ) == 5 ) {
x = ( ( ( ( ( d[ 0 ] << 8 ) + d[ 1 ] ) << 8 )
+ d[ 2 ] ) << 8 ) + d[ 3 ];
printf( "x = %x\n", x );
}

return 0;
}
Great thanks Jens. It works fine for one line so I have to figure out
how I can parse the whole txt file :)

Cheers!
Aug 15 '07 #4
I modified the code from jens slightly, but
it looks like the program sticks with the
first line it reads from "icache.dat ". Why
does the program not move to the next line of
the text file after the fscanf and remains with the
first one?

int main( void ) {
FILE *fp = fopen( "icache.dat ", "r" );
unsigned int d[ 4 ];
unsigned int x;

if ( fp == NULL )
return EXIT_FAILURE;

while ( fscanf( fp, "%x%x%x%x%" , d, d + 1, d + 2, d + 3 ) != EOF )
{
x = ( ( ( ( ( d[ 0 ] << 8 ) + d[ 1 ] ) << 8 )
+ d[ 2 ] ) << 8 ) + d[ 3 ];
printf( "x = %x\n", x );
}
return 0;
}

Cheers!
Aug 15 '07 #5
Roman Zeilinger wrote:
I modified the code from jens slightly, but
it looks like the program sticks with the
first line it reads from "icache.dat ". Why
does the program not move to the next line of
the text file after the fscanf and remains with the
first one?
Time for the C FAQ, I suspect. http://c-faq.com

There's loads of discussion of the pitfalls and snares of scanf..
Aug 15 '07 #6
Roman Zeilinger <Ro************ *@yahoo.dewrote :
I modified the code from jens slightly, but
it looks like the program sticks with the
first line it reads from "icache.dat ". Why
does the program not move to the next line of
the text file after the fscanf and remains with the
first one?
int main( void ) {
FILE *fp = fopen( "icache.dat ", "r" );
unsigned int d[ 4 ];
unsigned int x;
if ( fp == NULL )
return EXIT_FAILURE;
while ( fscanf( fp, "%x%x%x%x%" , d, d + 1, d + 2, d + 3 ) != EOF )
{
x = ( ( ( ( ( d[ 0 ] << 8 ) + d[ 1 ] ) << 8 )
+ d[ 2 ] ) << 8 ) + d[ 3 ];
printf( "x = %x\n", x );
}
return 0;
}
If there are some unusable data in that line as in your origi-
nal example had you don't skip them. fscanf() will try to read
them also as 4 hex numbers, fail for obvious reasons, return 0
and not move forward in the file. And you only test the return
value for EOF and repeat if you get anything else. That makes
fscanf() look again at the stuff it already deemed as not being
4 hex numbers the last time round, giving you the same result
again etc., so you end up in an endless loop. That's why I had
proposed to either read in everything of the remainder of the
line with a loop over getc() until you find the newline charac-
terer or by using a long enough dummy buffer that gets filled
with the unusable data in the call of fscanf().

Regards, Jens
--
\ Jens Thoms Toerring ___ jt@toerring.de
\______________ ____________ http://toerring.de
Aug 15 '07 #7
jt@toerring.de (Jens Thoms Toerring) writes:
Roman Zeilinger <Ro************ *@yahoo.dewrote :
>I modified the code from jens slightly, but
it looks like the program sticks with the
first line it reads from "icache.dat ". Why
does the program not move to the next line of
the text file after the fscanf and remains with the
first one?
>int main( void ) {
FILE *fp = fopen( "icache.dat ", "r" );
unsigned int d[ 4 ];
unsigned int x;
> if ( fp == NULL )
return EXIT_FAILURE;
> while ( fscanf( fp, "%x%x%x%x%" , d, d + 1, d + 2, d + 3 ) != EOF )
{
x = ( ( ( ( ( d[ 0 ] << 8 ) + d[ 1 ] ) << 8 )
+ d[ 2 ] ) << 8 ) + d[ 3 ];
printf( "x = %x\n", x );
}
return 0;
}

If there are some unusable data in that line as in your origi-
nal example had you don't skip them. fscanf() will try to read
them also as 4 hex numbers, fail for obvious reasons, return 0
and not move forward in the file.
For this reason it is almost always better to test the return value
from fscanf for success (== 4 in this case) rather than for one
particular failure (from the possible EOF, 0, 1, 2 or 3).

--
Ben.
Aug 15 '07 #8
Roman Zeilinger wrote:
>
Hi

I have a beginner question concerning fscanf.
First I had a text file which just contained some
hex numbers:

0C100012
0C100012
...

It was easy to read this values into an integer variable:

FILE *fp = fopen("test.dat ","r");
int mem_word = 0;
while (fscanf(fp,"%x" , &mem_word) != EOF)
...

Now, I have the following format where my hex number
is splitted by spaces. So I wonder if there is
an easy way to parse such a line and not doing
a lot of space removing etc.

0C 10 00 12 // 00000000
0C 10 00 12 // 00000000
...

Thanks for helpful comments.
I like to read lines and proccess strings.

/* BEGIN beginner.c */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <assert.h>

#define FILE_NAME ("test.dat")
#define LINE ("0C 10 00 12")
#define LINELENGTH 11
#define str(x) # x
#define xstr(x) str(x)

void hex_squeeze(cha r *s1);

int main(void)
{
unsigned long mem_word;
char array[sizeof LINE];
int rc;
char *endptr;
char *fn = FILE_NAME;
FILE *fp = fopen(fn, "r");

assert(LINELENG TH == sizeof LINE - 1);
fp = fopen(fn, "r");
if (fp == NULL) {
printf("fopen problem with %s\n", fn);
exit(EXIT_FAILU RE);
}
do {
rc = fscanf(fp, "%" xstr(LINELENGTH ) "[^\n]%*[^\n]", array);
if (!feof(fp)) {
getc(fp);
}
if (rc == 0) {
array[0] = '\0';
}
if (rc == 1) {
hex_squeeze(arr ay);
mem_word = strtoul(array, &endptr, 16);
printf("%lx\n", mem_word);
}
} while (rc != EOF);
fclose(fp);
return 0;
}

void hex_squeeze(cha r *s)
{
char *p = s;

do {
if (isxdigit((unsi gned char)*s)) {
*p++ = *s;
}
} while (*s++ != '\0');
*p = '\0';
}

/* END beginner.c */
--
pete
Aug 16 '07 #9
In article <5i************ *@mid.uni-berlin.de>
Jens Thoms Toerring <jt@toerring.de wrote:

[a bunch of correct stuff with one subtle flaw]
unsigned int d[ 4 ];
unsigned int x;
[snippage]
x = ( ( ( ( ( d[ 0 ] << 8 ) + d[ 1 ] ) << 8 )
+ d[ 2 ] ) << 8 ) + d[ 3 ];
printf( "x = %x\n", x );
To make this portable, you need to give "x" the type "unsigned
long", and convert at least one of the various operands in the
shift and add sequence to "unsigned long". Of course then the
printf() format argument must be "%lx".

(An implementation with 16-bit "unsigned int"s will turn:

x = (((((d[0] << 8) + d[1]) << 8) + d[2]) << 8) + d[3];

into the equivalent of just:

x = (d[2] << 8) + d[3];

since the extra bits will "fall off the end". A lot of
implementations today have 32-bit "int", where the problem
will not occur; and some of 64-bit "long", where "unsigned
long" is perhaps overkill, but the oberkill is portable.)
--
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.
Aug 16 '07 #10

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

Similar topics

1
2212
by: siliconwafer | last post by:
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) {
5
2996
by: Fra-it | last post by:
Hi everybody, I'm trying to make the following code running properly, but I can't get rid of the "SEGMENTATION FAULT" error message when executing. Reading some messages posted earlier, I understood that a segmentation fault can occur whenever I declare a pointer and I leave it un-initialized. So I thought the problem here is with the (const char *)s in the stuct flightData (please note that I get the same fault declaring as char * the...
2
1544
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";
18
2923
by: mitchellpal | last post by:
Hi guys, am learning c as a beginner language and am finding it rough especially with pointers and data files. What do you think, am i being too pessimistic or thats how it happens for a beginner? Are there better languages than c for a beginner? For instance visual basic or i should just keep the confidence of improving?
6
8407
by: c_beginner | last post by:
yes, this is my how work question. Since I am lack in getting an assistance with my lab work I put this in this advance group. Sorry for the trouble I am making. Write a program to calculate the compound interest. #include<stdio.h> #include<stdlib.h> double intrest(double tot_amount,float percent) {
9
1533
by: raam | last post by:
hi all, I trying to write an array of integers into a text file.While writing into the file it works.I used fwrite function, but when I read the same file using fread or fscanf it fails and it prints some junk.I am not opening the file in binary mode, there are no characters which will terminate the fscanf function operation.How to write and read the integer array . Thanks in advance.
7
3141
by: blacksoil | last post by:
Hi, I have a question regarding reading data from a file and put it to a member of a class. I use fscanf. The class looks like this class myclass { double a;
3
6692
by: totoro2468 | last post by:
Hi, I'm a complete NOOB. How do I get fscanf to copy into an array? I also need to use malloc, but where do I put it in my file? _______________________________________________________ FILE *ifp; char c; int y = 0; txtFile = (char *) malloc(FILELENGTH * sizeof(char)) ;
59
5583
by: David Mathog | last post by:
Apologies if this is in the FAQ. I looked, but didn't find it. In a particular program the input read from a file is supposed to be: + 100 200 name1 - 101 201 name2 It is parsed by reading the + character, and then sending the remainder into fscanf() like
0
8818
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,...
1
9305
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
8231
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
6790
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
6067
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
4588
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
3296
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
2
2771
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2203
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.