943,929 Members | Top Members by Rank

Ad:
  • C Discussion Thread
  • Unsolved
  • Views: 3898
  • C RSS
Nov 26th, 2008
0

Read file using fget

Expand Post »
I have the following in a text file

How old are you?:I am 1 year old.

Basically, the ":" is the delimiter. "How old are you?" is the question and "I am 1 year old" is what i will reply when i get the question .

There is basically 2 fields in this. I know in C++ i can just do a getline(cin, question, answer, specifying the delimiter.

however, i cant do that in c? is there a better way to do it? store the first field in one string variable and 2nd field in another stirng variable?
Similar Threads
Reputation Points: 6
Solved Threads: 0
Light Poster
AcidG3rm5 is offline Offline
25 posts
since Oct 2008
Nov 26th, 2008
0

Re: Read file using fget

strtok()
Reputation Points: 888
Solved Threads: 114
Nearly a Posting Virtuoso
MosaicFuneral is offline Offline
1,270 posts
since Nov 2008
Nov 26th, 2008
0

Re: Read file using fget

Read the whole line with fgets()

Tokenise is with strchr(), strtok() or anything else you can think of.
Team Colleague
Reputation Points: 5862
Solved Threads: 950
Posting Sage
Salem is offline Offline
7,164 posts
since Dec 2005
Nov 26th, 2008
0

Re: Read file using fget

I've tried using fgets to read whole line.

However, it only reads the first line and end from there. Did i forget to put a loop or something?

Quote ...
#include <stdio.h>


int main()
{
FILE * pFile;
char mystring [300];

pFile = fopen ("question.txt" , "r");
if (pFile == NULL) perror ("Error opening file");
while(fgets (mystring , 300 , pFile)) {
fgets (mystring , 300 , pFile);
puts (mystring);
fclose (pFile);
system("pause");
}
return 0;
}
Reputation Points: 6
Solved Threads: 0
Light Poster
AcidG3rm5 is offline Offline
25 posts
since Oct 2008
Nov 26th, 2008
0

Re: Read file using fget

You call fgets() twice, then close the file INSIDE the loop.

So yeah, you only go round the once.
Team Colleague
Reputation Points: 5862
Solved Threads: 950
Posting Sage
Salem is offline Offline
7,164 posts
since Dec 2005

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C Forum Timeline: Odd result in fscanf
Next Thread in C Forum Timeline: need help: shuffle 2-dimensional array





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC