473,804 Members | 2,999 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Strange issue with fscanf and fgets

52 New Member
Hey bytes community!

this one is a really strange issue I ran into and I'm hoping you all can shine some light on it for me.

This is written in C, not C++

I'm working on a program that reads in information from a txt file and outputs it sorted into another txt file.

the code to read from the file looks like this

Expand|Select|Wrap|Line Numbers
  1.     fscanf(fin, "%d", &size);
  2.     deptList = (struct dept*)(malloc(size*sizeof(struct dept)));
  3.  
  4.     for (i=0; i<size; i++) {
  5.  
  6.         fgets(line, MAXLEN, fin);
  7.         strtok(line, delims);
  8.         strcpy(deptList[i].name, line);
  9.  
  10.         p = (char*)strtok(NULL, delims);
  11.         deptList[i].numFaculty = atoi(p);
  12.  
  13.         p = (char*)strtok(NULL, delims);
  14.         deptList[i].totalSalary = atoi(p);  
  15.  
  16.         // Not used.
  17.         p = (char*)strtok(NULL, delims);
  18.  
  19.     }
  20.  
first it reads a number on the first line that lets it know how many lines are to follow. then it allocates memory and reads each line and breaks it up.

Here's the problem. When it starts reading the items into the array the first index (0) doesn't get any information and the second index (1) gets the information from the second line in the file (information that should be in the first index(0))

for the life of me I can't figure out why this isn't working, but i have a suspision that the cursor is left on the first line of the file after the fscanf() call and thus the first fgets() is reading the end of that line and not the second... but like i said... i have no idea.

Any help would be appreciated!
May 19 '08 #1
3 2871
gpraghuram
1,275 Recognized Expert Top Contributor
Hey bytes community!

this one is a really strange issue I ran into and I'm hoping you all can shine some light on it for me.

This is written in C, not C++

I'm working on a program that reads in information from a txt file and outputs it sorted into another txt file.

the code to read from the file looks like this

Expand|Select|Wrap|Line Numbers
  1.     fscanf(fin, "%d", &size);
  2.     deptList = (struct dept*)(malloc(size*sizeof(struct dept)));
  3.  
  4.     for (i=0; i<size; i++) {
  5.  
  6.         fgets(line, MAXLEN, fin);
  7.         strtok(line, delims);
  8.         strcpy(deptList[i].name, line);
  9.  
  10.         p = (char*)strtok(NULL, delims);
  11.         deptList[i].numFaculty = atoi(p);
  12.  
  13.         p = (char*)strtok(NULL, delims);
  14.         deptList[i].totalSalary = atoi(p);  
  15.  
  16.         // Not used.
  17.         p = (char*)strtok(NULL, delims);
  18.  
  19.     }
  20.  
first it reads a number on the first line that lets it know how many lines are to follow. then it allocates memory and reads each line and breaks it up.

Here's the problem. When it starts reading the items into the array the first index (0) doesn't get any information and the second index (1) gets the information from the second line in the file (information that should be in the first index(0))

for the life of me I can't figure out why this isn't working, but i have a suspision that the cursor is left on the first line of the file after the fscanf() call and thus the first fgets() is reading the end of that line and not the second... but like i said... i have no idea.

Any help would be appreciated!

Can you post the file which is being read by the code?

Raghuram
May 20 '08 #2
oler1s
671 Recognized Expert Contributor
thus the first fgets() is reading the end of that line and not the second...
Good guess. Let me explain what your code actually does, because of how fscanf and fgets work.

fscanf takes input you give it, and tries to format and store it appropriately. Let's say I wanted to enter the number 5. I hit the keys, 5, and then enter. That's two characters: the character for 5, and the character that matches a newline. fscanf works on this input; it processes the '5' as the number 5. But the newline is not a number, so it's left right in the input stream.

Now fgets runs. Fgets stops reading (and storing the input) when it reaches a newline. But wait, what about the newline already in the stream? It's still there, so fgets picks that up...and then stops. Not what you wanted. You really wish that newline would not stay there.

What I really recommend you do, is avoid using the scanf family. You can always manually parse input as a number using atoi or preferrably strtol. So just use fgets/strtol to do the number input.

What's with the char* cast for strtok? Also, I don't recommend you cast malloc. Casting malloc isn't actually necessary. Furthermore, the cast cannot help you, but it may hurt. The recommended form for malloc is
Expand|Select|Wrap|Line Numbers
  1. p = malloc(n * sizeof *p)
May 20 '08 #3
Shisou
52 New Member
Good guess. Let me explain what your code actually does, because of how fscanf and fgets work.

fscanf takes input you give it, and tries to format and store it appropriately. Let's say I wanted to enter the number 5. I hit the keys, 5, and then enter. That's two characters: the character for 5, and the character that matches a newline. fscanf works on this input; it processes the '5' as the number 5. But the newline is not a number, so it's left right in the input stream.

Now fgets runs. Fgets stops reading (and storing the input) when it reaches a newline. But wait, what about the newline already in the stream? It's still there, so fgets picks that up...and then stops. Not what you wanted. You really wish that newline would not stay there.

What I really recommend you do, is avoid using the scanf family. You can always manually parse input as a number using atoi or preferrably strtol. So just use fgets/strtol to do the number input.

What's with the char* cast for strtok? Also, I don't recommend you cast malloc. Casting malloc isn't actually necessary. Furthermore, the cast cannot help you, but it may hurt. The recommended form for malloc is
Expand|Select|Wrap|Line Numbers
  1. p = malloc(n * sizeof *p)
YAY! I was close! thank you so much for clearing that up for me I'll test using another fgets after i post this.

Also, the casting done in the program was actually done by my professor so don't look at me :\

Thanks again!

p.s. the professor also had this same problem in his program that he showed to the class XP
May 20 '08 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

4
1881
by: Materialised | last post by:
Hi everyone, I have the following program #include <stdio.h> #include <stdlib.h> int main(void) { FILE *fp1, *fp2; char s;
3
6736
by: Benedicte | last post by:
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 ***/
7
2831
by: Kay | last post by:
1) If i want to read data from a txt file, eg John; 23; a Mary; 16; i How can I read the above data stopping reading b4 each semi-colon and save it in three different variables ? 2) If I enter a number, can I use to call a particular node ? eg enter a number: 3 calling node of number 3 is it possible ?
5
424
by: learner | last post by:
I have datafiles like this: 0 1941 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.02 0.00 0.00 1 0 1941 0.00 0.03 0.00 0.03 0.04 0.02 0.00 0.00 0.00 0.00 2 0 1941 0.00 0.00 0.00 0.00 0.52 0.00 0.00 0.17 1.07 0.09 3 0 1941 0.04 0.00 0.00 0.00 0.00 0.62 0.00 0.01 0.00 0.00 4 0 1941 0.00 0.02 0.00 0.00 0.00 0.22 0.00 0.00 0.00 0.16 5 0 1941 0.00 0.00 0.00 0.00 0.09 0.04 0.00 0.00 0.00 0.00 6 0 1941 0.00...
9
2372
by: kvnsmnsn | last post by:
Over the course of my career I've transitioned from an Ada programmer (am I dating myself?) to a C programmer to a Java programmer and now back to a C programmer with the job I've currently started. What I'd like to do is write a piece of C code that inputs to the pro- gram a line written to a file. The Java code written below does exactly what I want; it writes the <String"ab cd" to file "Java.Txt" and then reads it back in to variable...
37
4981
by: PeterOut | last post by:
I am using MS Visual C++ 6.0 on Windows XP 5.1 (SP2). I am not sure if this is a C, C++ or MS issue but fscanf has been randomly hanging on me. I make the call hundreds, if not thousands, of times but it hangs in different places with the same data. The offending code follows. ReadFile(char *csFileName) { float fFloat1, fFloat2;
59
5599
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
5
2315
by: a | last post by:
After reading FAQ comp.lang.c section 12 and googling again, still there is no threads talking about reading a series of numbers. The input files, somehow structured, is exemplified below: <presence/absence of n space/tab on the first n lines> 12 <presence/absence of n space/tab here>0<presence/absence of n space/tab here>90 10 23 43 0 0 0 0 0 0 0 90 0 0 0 0 88 0 0 0 ...
42
3825
by: Bill Cunningham | last post by:
I'm doing something wrong and all I know to do is turn to clc. I have a text file containing 2 doubles separated by a tab. ..26 0 Is the text. I want to read the two double and printf them out. Here's my file. #include <stdio.h>
0
9704
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10562
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
10319
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
7608
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
6845
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
5508
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...
0
5639
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4282
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
2978
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.