In article <d7d31bfd.0402040306.48410644@posting.google.com >,
Benedicte <benelive@hotmail.com> wrote:[color=blue]
>Hi,
>
>I'm getting some problems when using fscanf to read a file.
>
>This is a piece of the program code:
>[/color]
It's great you posted a working program, but please rember to
also include apropriate headers, e.g.: 'stdio.h' in this case.
[color=blue]
>main ()
>{
> /*** Variable declaration ***/
> FILE *vpfile; /*** Data file ***/
>
> struct line
> {
> char old_al[10];
> char new_al[10];
> char vp[5];
> char new_dl[17];
> };
> struct line l[1000]={0};
> int i=0;
> int nl=0; /*** number of lines read ***/
> int res=0;
>
> /*** Executable statements ***/
> /*** Open VpMove.txt file ***/
> vpfile=fopen("/export/home/granite/CAPI/prog/bin/VpMove.txt","r");
> if(vpfile==NULL)
> {
> printf("The file VpMove.txt could not be opened\n");
> return;
> }
> /*** Read datafile ***/
> while(fscanf(vpfile,"%s",l[i].old_al)!=EOF)
> {
> fscanf(vpfile,"%s",l[i].new_al);
> fscanf(vpfile,"%s",l[i].vp);
> fscanf(vpfile,"%s",l[i].new_dl);
> i++;
> }
> nl=i-1; /*** undo i++ ***/
> for(i=0;i<=nl;i++)
> {
> printf("Line %d %s\t %s\t %s\t
>%s\n",i,l[i].old_al,l[i].new_al,l[i].vp,l[i].new_dl);
> }
> fclose(vpfile);
>}
>
>The VpMove.txt file looks like this:
>003360073 003362061 240 AP-B_LIE_PP01-523
>003360073 003351154 244 AP-B_LIE_PP01-10
>003360073 003351154 243 AP-B_LIE_PP01
>
>The output is the following:
>Line 0 003360073 003362061 240 AP-B_LIE_PP01-523003360073
>Line 1 003360073 003351154 244 AP-B_LIE_PP01-10
>Line 2 003360073 003351154 243 AP-B_LIE_PP01
>
>The problem is that when the word ends with a minus sign followed by 3
>digits (see first line) he takes directly the following word: so
>instead of AP-B_LIE_PP01-523 I receive AP-B_LIE_PP01-523003360073.
>
>Can someone help me on this one?????[/color]
The problem is that you overflow the character array of 'new_dl' fields.
This array is 17 characterss big, 'AP-B_LIE_PP01-523' has 17 characters,
leaving no space for the '\0' (zero terminator) that fscanf(...) wants
to insert at the end. When you print the value of 'new_dl' you run into
UB since printf expects a zero terminator to end strings. You might
find this zero terminator at the first field of the next record, that
explains the '003360073' part.
Increase the size of 'new_dl' from 17 to 18 and you'll see it works,
this is of course by no means a constructive solution.
Regards,
--
Rob van der Leek | rob(at)ricardis(dot)tudelft(dot)nl
Ricardishof 73-A |
http://www.ricardis.tudelft.nl/~rob
2614 JE Delft, The Netherlands
+31 (0)6 155 244 60