954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Read file using fget

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?

AcidG3rm5
Light Poster
25 posts since Oct 2008
Reputation Points: 6
Solved Threads: 0
 

strtok()

MosaicFuneral
Posting Virtuoso
1,691 posts since Nov 2008
Reputation Points: 888
Solved Threads: 116
 

Read the whole line with fgets()

Tokenise is with strchr(), strtok() or anything else you can think of.

Salem
Posting Sage
Team Colleague
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
 

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?

#include

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; }

AcidG3rm5
Light Poster
25 posts since Oct 2008
Reputation Points: 6
Solved Threads: 0
 

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

So yeah, you only go round the once.

Salem
Posting Sage
Team Colleague
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You