Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to read this kind of file by using C.

Status
Not open for further replies.

qingxing2005

Technical User
Sep 2, 2006
6
SE
Dear all,

I met one problem when reading the following context file by using C. E.g. abc: 123123,123123123,123123123

I use the statement, i.e. fscanf(fp_t, "%s %d %d %d", stringA, cl[0], cl[1], c[2]);

However, the values cannot be read and put to the variable cl[1], cl[2]. Only reading value and putting it to cl[0] is feasible.

Is there anyone can help a little?

Thanks in advance,
 
Read each line into a string, then parse the string (maybe strtok() would help), then use something like atoi() to convert each sub-string into a number...
 
And don't forget to add get address (&) operation for all variables (except arrays) in scanf family arg list.

It's interesting that in some implementations (MS and may Unix) you may use %s specificator non-standard extension:
Code:
fscanf(fp_t,"%[^:]%d,%d,%d", stringA,&cl[0],&cl[1],&c[2]);
It's a very dangerous (and non-standard) code: for example, no scanf return code check (do it in all cases). Better use cpjust's good advice.
 
Hey,

I also tried following code, it works somewhat for my case. However, with something little not. See followings.

The context file to be read is, i.e.

abc:1111111111,2222222222,3333333333,4444444444,5555555555,6666666666,
d: 0
efg: 1111111111,2222222222,3333333333,4444444444,5555555555,6666666666

1. the outputs of reading 4444444444,5555555555 are 149477148 1260588259. by using this sentence,

fscanf(fp_t, "%s %10d , %10d , %10d , %10d , %10d , %10d", stringA, &cl[0], &cl[1], &c[2], &cl[3], &cl[4], &c[5]);

It is weird.

 
You're running into integer overflow, as explained on cprogramming.com already.


--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top