473,757 Members | 9,463 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problems when reading from a file with fscanf

Hi,

I'm getting some problems when using fscanf to read a file.

This is a piece of the program code:

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(vp file,"%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?????
Nov 14 '05 #1
3 6734
In article <d7************ **************@ posting.google. com>,
Benedicte <be******@hotma il.com> wrote:
Hi,

I'm getting some problems when using fscanf to read a file.

This is a piece of the program code:

It's great you posted a working program, but please rember to
also include apropriate headers, e.g.: 'stdio.h' in this case.
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(vp file,"%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?????


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(do t)nl
Ricardishof 73-A | http://www.ricardis.tudelft.nl/~rob
2614 JE Delft, The Netherlands
+31 (0)6 155 244 60
Nov 14 '05 #2
Benedicte wrote:

struct line
{
char old_al[10];
char new_al[10];
char vp[5];
char new_dl[17];
};
So you have allocated 17 charecters for new_dl
fscanf(vpfile," %s",l[i].new_dl);
fscanf has wrote 18 charecters to new_dl. So undefined behavior.
Really it has wrote ending '\0' to the old_al of the second array member.
nl=i-1; /*** undo i++ ***/
for(i=0;i<=nl;i ++)
{


for (i = 0; i < nl; i++)
is consider to be standart among programmers. So use it insted of
decreasing nl

Using scanf is not safe because of buffer overrun as in your example.
You can use fgets and break the line into tokens by strtok or strpbrk
If you don't like fgets you can use some thing like:

char *afgets (char *s, size_t *lenp, FILE *f)
{
char *t;
ptrdiff_t tmp;
size_t l = 0;

if (lenp)
l = *lenp;
if (!s)
l = 0;
if (l == 0) {
l = 10;
s = malloc (l);
}
t = s;
for (;;) {
fgets (t, l, f);
t += strlen (t) - 1;
if (*t == '\n' || feof (f))
break;
tmp = t - s;
if ((t = realloc (s, l *= 2)) == NULL) {
l /= 2;
break;
}
s = t;
t += tmp;
}
if (lenp)
*lenp = l;
return s;
}

Nov 14 '05 #3


Benedicte wrote:
Hi,

I'm getting some problems when using fscanf to read a file.

This is a piece of the program code: #include <stdio.h>
main () int main(void)
{
/*** Variable declaration ***/
FILE *vpfile; /*** Data file ***/

struct line
{
char old_al[10];
char new_al[10];
char vp[5];
char new_dl[17];
};
You have not made some of the character arrays in the struct large
enough for the data. Looking at the data you supplied:

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 struct, at a minimum should be:

struct line
{
char old_al[11]; /* allows enough for the string ending '\0' char */
char new_al[11];
char vp[4];
char new_dl[18];
};
struct line l[1000]={0};
int i=0;
int nl=0; /*** number of lines read ***/
int res=0;
What is res used for?
/*** 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;
main returns an int. You could make this:
return 1; }
/*** Read datafile ***/
while(fscanf(vp file,"%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);
}
You can modify the above to:

for(nl = 0; 4 == fscanf(vpfile, " %s %s %s %s ",l[nl].old_al,
l[nl].new_al, l[nl].vp, l[nl].new_dl) ; nl++) ;
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);
return 0; }


--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapi dsys.com (remove the x to send email)
http://www.geocities.com/abowers822/

Nov 14 '05 #4

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

Similar topics

28
9584
by: Colin JN Breame | last post by:
Hi, Fairly new to C. What is the best way to read a line (\n terminated) from a file? Ive looked at fscanf but was not sure which format specifier to use. (%s perhaps). Thanks Colin
1
1458
by: bas | last post by:
hey, I am having a lot of trouble trying to get this program to work. It is supposed to read integers from a file and place them into the categories for inventory. The problem seems to be that the program is only reading the first line of numbers from the text file and printing them in ever category. Any help or suggestions woulud be great, I swear i probably tried everything #include <stdio.h>
6
1787
by: bas | last post by:
hey, I am having a lot of trouble trying to get this program to work properly. It is supposed to read integers from a file and place them into the categories for inventory. The problem seems to be that the program will only read the first line of integers from the file, and just print them into all the categories. Any help or suggestions woulud be great, I swear i probably tried everything #include <stdio.h>
29
10432
by: yourmycaffiene | last post by:
Okay, this if my first post so go easy on me plus I've only been using C for a couple of weeks. I'm working on a program currently that requires me to read data from a .dat file into a 2d array and then print out the contents of the 2d array to the screen. I wil also need to append data to the .dat file but mostly right now I'm worrying about getting the info into the 2d array. My .dat file looks like this 1 20000 2 30000 3 40000
4
4232
by: John | last post by:
I need to read data from the file like the following with name and score, but some line may only has name without score: joe 100 amy 80 may Here's my code, but it couldn't read the line with "may" because there is no score. Anyone knows what is the workaround to this problem?
10
3182
by: lancer6238 | last post by:
Hi all, I'm having programs reading from files. I have a text file "files.txt" that contains the names of the files to be opened, i.e. the contents of files.txt are Homo_sapiens.fa Rattus_norvegicus.fa (They are FA files that can be opened in any text editor.)
2
1479
by: ajay0419 | last post by:
Hi: I am trying to read from a file, which stores answers for a particular question(The answers are stop listed ). Each answer in the file is enclosed in opening and closing braces. Here is the sample file { tenets nutrigenomics jim kaput improper diets risk factors disease dietary chemicals alter gene expression andor genome diseases } { individuals nutritional needs a result own genetic } I am trying to read from this file and...
5
5041
by: imailz | last post by:
Hi all, since I'm forced to switch from Fortran to C I wonder if there is posibility in C: 1) to use implicit loops 2) to parse several variables which number is determined at runtime. Following example: The output contains n columns which have to be read in. The number of
3
1988
by: godblessingme | last post by:
Hi, I'm getting some problems when using fscanf to read a file. This is a piece of the program code: #include <stdlib.h> #include <stdio.h> int main() {
0
9298
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
10072
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
9737
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8737
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
7286
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
6562
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
5329
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3829
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
3
3399
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.