I want to know how to read from a file. I have posted the first line of program.dat file before. There are more than one line in the file and i want to tokenize them and save them into different variables or pointers. Can anyone write full code how to do it. I did with strtok and it doesn't read last line. I used fgets to read each line of file

P0001|UG|Bachelor of Computer Science|Application Programming|BP094|3|FT|The Bachelor of Computer Science degrees develop a skill set that spans from theoretical and algorithmic foundations to cutting-edge developments in computing.|In this major, you will gain skills in developing practical coding solutions for the widest range of real-world problems using the latest software development skill sets.
Comments
okay, lets not totally brutalize the guy, here.... (lol at tux :)
This ain't a code snippet. And we don't do other people's homework
Computer Science? You can't even start a thread :(

There are a number of ways to do it. One way is to use strtok() to find each segment of the string.

You gave the guy a full bad reputation because you felt he did not follow "the rules", for soliciting code, and whatnot. However, that did not prevent you from making another irrelevant post, endorsing strtok(), an amateur use of it. Which, regardless, the guy said already he was using, but somehow it was not reading the last line.
Good job Mr. AD, you are getting better and better. :icon_rolleyes:

javedkhan0258> did with strtok and it doesn't read last line. I used fgets to read each line of file
Post the code you said you did in a regular thread in this forum, and we might give it a look and see what's wrong with it.

Edited 6 Years Ago by Aia: n/a

Comments
Fully recover from the undeserved bad rep :)
hi
go away

if you're getting all but the last line, the reason is probably that your while loop is not constructed correctly.

like aia said, post the code.

You gave the guy a full bad reputation because you felt he did not follow "the rules", for soliciting code, and whatnot. However, that did not prevent you from making another irrelevant post, endorsing strtok(), an amateur use of it. Which, regardless, the guy said already he was using, but somehow it was not reading the last line.
Good job Mr. AD, you are getting better and better. :icon_rolleyes:

javedkhan0258> did with strtok and it doesn't read last line. I used fgets to read each line of file
Post the code you said you did in a regular thread in this forum, and we might give it a look and see what's wrong with it.

Response from Mr AD, as always, via negative reputation tab: go away - Ancient Dragon
Keep showing your bully trademark!

I was going to say something really nasty but decided not to. Feel lucky that's all I said to you. And you are going to get negative rep from me every time you decide to spout off your fowel mouth.

Edited 6 Years Ago by Ancient Dragon: n/a

I was going to say something really nasty but decided not to. Feel lucky that's all I said to you. And you are going to get negative rep from me every time you decide to spout off your fowel mouth.

And I am going to call you on every time you decide to post for the only reason of just posting, some with little or not insight in the matter, some with contemptuous remarks and rotten advise.
I will do it in open and in clear terms so my peers can judge, not you.

P0001|UG|Bachelor of Computer Science|Application Programming|BP094|3|FT|The Bachelor of Computer Science degrees develop a skill set that spans from theoretical and algorithmic foundations to cutting-edge developments in computing.|In this major, you will gain skills in developing practical coding solutions for the widest range of real-world problems using the latest software development skill sets.

The code above in program.dat file is actually in one line don't get confused. There are many lines like above for many program's attribute.

My code is something like this

File *fp;
char *progId;
    	char *progType;
    	char *progTitle;
    	char *progMajor;
    	char *progCode;
    	char *progDur;
    	char *progMode;
    	char *progDescription;
    	char *majorDescription;

 if(!(fp=fopen(programFile, "r"))){
             printf("Error occurered while opening the program.dat file");
             return 0;                             
  }     

while(fgets(length,LINE_LENGTH,fp) !=NULL)
 {
prev = NULL;
            curr = pms->headProgram;
            idTok = strtok(length, ":");
	     	 
    	 progId=strtok(arra[i],"|");
	
	 if(progId==NULL){
		printf("\nprogID is NULL\n");
	 }
    	 progType = strtok(NULL, "|");
	 if(progType==NULL){
		printf("progType is NULL\n");
		break;
	 }
         progTitle=strtok(NULL,"|");
	 if(progTitle==NULL){
		printf("progTitle is NULL\n");
		break;
	 }
    	 progMajor=strtok(NULL,"|");
	 if(progMajor==NULL){
		printf("progMajor is NULL\n");
		break;
	 }
    	 progCode=strtok(NULL,"|");
	 if(progCode==NULL){
	 	printf("progCode is NULL\n");
		break;
	 } 
  	 progDuration=atoi(strtok(NULL,"|"));
	 if(progDuration==NULL){
		printf("progCode is NULL\n");
		break;
	 }
       	 progMode=strtok(NULL,"|");
	 if(progMode==NULL){
  		printf("progMode is NULL\n");
		break;
	 }
    	 progDescription=strtok(NULL,"|");
	 if(progDescription==NULL){
	 	printf("progMode is NULL\n");
		break;
         }    
  
       
    	majorDescription=strtok(NULL,"|");
	if(majorDescription==NULL){
		printf("majorDescription is NULL\n");
		break;
	}


  }

The problem is when it reads the last line it shows that majorDescription is NULL? Why?

Edited 6 Years Ago by __avd: Added [code] tags. For easy readability, always wrap programming code within posts in [code] (code blocks).

if you're getting all but the last line, the reason is probably that your while loop is not constructed correctly.

like aia said, post the code.

I have uploaded the program.dat file but I changed the format to program.xml. I posted the code to implement this in forum before

Attachments
P0001|UG|Bachelor of Computer Science|Application Programming|BP094|3|FT|The Bachelor of Computer Science degrees develop a skill set that spans from theoretical and algorithmic foundations to cutting-edge developments in computing.|In this major, you will gain skills in developing practical coding solutions for the widest range of real-world problems using the latest software development skill sets.
P0002|UG|Bachelor of Computer Science|Computational Mathematics|BP094|3|FT|The Bachelor of Computer Science degrees develop a skill set that spans from theoretical and algorithmic foundations to cutting-edge developments in computing.|In this major, you will expand your computer science knowledge with courses in Mathematics to enable you to work in areas of computing where more complex knowledge of mathematical modelling need to be automated.
P0003|UG|Bachelor of Information Technology|Business Applications|BP162|3|FT|The Bachelor of Information Technology degree trains students to make a living solving, supporting, troubleshooting and designing  from web sites to business applications to programming networks.|In this major, you will be exposed to specific applications of information technology to the business world.
P0004|UG|Bachelor of Information Technology|Multimedia Design|BP162|3|FT|The Bachelor of Information Technology degree trains students to make a living solving, supporting, troubleshooting and designing  from web sites to business applications to programming networks.| you will focus your IT skills on the creative world of Web and Time Based Media, Narrative for Multimedia, Advanced 3D Imaging, Animation and Multimedia Authoring, etc.
P0005|PG|Master of Information Technology|N/A|MC061|1.5|FT|This program is designed for computer science graduates who want to study advanced postgraduate-level computing and gain exposure to world-class technologies.|N/A.
P0006|PG|Master of Computing|N/A|MC062|3|PT|The Master of Computing program is designed for non-computing graduates with good grades in their first university degree.|N/A.
P0007|UG|Bachelor of Software Engineering|BP096|4|FT|The Bachelor of Software Engineering degree is centred on the development and management of larger quality-measured software systems|N/A

javedkhan0258> The problem is when it reads the last line it shows that majorDescription is NULL? Why?
I don't believe so. The problem is much sooner than that.
strtok()modifies the original string, inserting '\0' for the delimiters, therefore it destroys the possibility of going back to it. That's why you enter NULL as the first parameter in the subsequent calls to strtok()

Take a look at this part: ~length is a line that you read from file.

idTok = strtok(length, ":"); /* <-- so far so good, first call from length */

progId=strtok(arra[i],"|"); /* <-- what? no null, now you are working in something different, lets hope it is a modifiabled string */

if(progId==NULL){
printf("\nprogID is NULL\n");
}
progType = strtok(NULL, "|"); /* <-- Another call to strtok, but where is reading from?, definitively not from length */
if(progType==NULL){
printf("progType is NULL\n");
break;

That's how much I am willing to go with you at this time. I do not endorse the use of strtok() but for trivial test. Nevertheless, you must learn somehow.

Edited 6 Years Ago by Aia: n/a

javedkhan0258> The problem is when it reads the last line it shows that majorDescription is NULL? Why?
I don't believe so. The problem is much sooner than that.
strtok()modifies the original string, inserting '\0' for the delimiters, therefore it destroys the possibility of going back to it. That's why you enter NULL as the first parameter in the subsequent calls to strtok()

Take a look at this part: ~length is a line that you read from file.

idTok = strtok(length, ":"); /* <-- so far so good, first call from length */

progId=strtok(arra[i],"|"); /* <-- what? no null, now you are working in something different, lets hope it is a modifiabled string */

if(progId==NULL){
printf("\nprogID is NULL\n");
}
progType = strtok(NULL, "|"); /* <-- Another call to strtok, but where is reading from?, definitively not from length */
if(progType==NULL){
printf("progType is NULL\n");
break;

That's how much I am willing to go with you at this time. I do not endorse the use of strtok() but for trivial test. Nevertheless, you must learn somehow.

int loadData(PMSType* pms, char* programFile, char* courseFile)
    {
    	
    	
    	FILE *fp;
    	
    	char *programLine;
    	
        if(!(fp=fopen(programFile, "r"))){
             printf("Error occurered while opening the program.dat file");
             return 0;                             
        }                             
          	        
    	char *progId;
    	char *progType;
    	char *progTitle;
    	char *progMajor;
    	char *progCode;
    	char *progDur;
    	char *progMode;
    	char *progDescription;
    	char *majorDescription;
    	int progDuration;
    	 
       
       ProgramType *prevProgram, *newProgram, *currProgram;
       
	char length[500];
	while(fgets(length,LINE_LENGTH,fp) !=NULL)
        {
            prevProgram = NULL;
            currProgram = pms->headProgram;
             	 
    	 progId=strtok(length,"|");
	
	 if(progId==NULL){
		printf("\nprogID is NULL\n");
	 }
    	 progType = strtok(NULL, "|");
	 if(progType==NULL){
		printf("progType is NULL\n");
		break;
	 }
         progTitle=strtok(NULL,"|");
	 if(progTitle==NULL){
		printf("progTitle is NULL\n");
		break;
	 }
    	 progMajor=strtok(NULL,"|");
	 if(progMajor==NULL){
		printf("progMajor is NULL\n");
		break;
	 }
    	 progCode=strtok(NULL,"|");
	 if(progCode==NULL){
	 	printf("progCode is NULL\n");
		break;
	 } 
  	 progDuration=atoi(strtok(NULL,"|"));
	 if(progDuration==NULL){
		printf("progCode is NULL\n");
		break;
	 }
       	 progMode=strtok("|");
	 if(progMode==NULL){
  		printf("progMode is NULL\n");
		break;
	 }
    	 progDescription=strtok(NULL,"|");
	 if(progDescription==NULL){
	 	printf("progMode is NULL\n");
		break;
         }    
  
       
    	majorDescription=strtok(NULL,"|");
	if(majorDescription==NULL){
		printf("majorDescription is NULL\n");
		break;
	}
	
	
    	printf("\n-----%s-----\n\n",progId);
    	printf("-----%s-----\n\n",progType);
     	printf("-----%s-----\n\n",progTitle);
     	printf("-----%s-----\n\n",progMajor);
     	printf("-----%s-----\n\n",progCode);
	printf("------%d----\n\n",progDuration);
    	printf("-----%s-----\n\n",progMode);
    	printf("-----%s-----\n\n",progDescription);
    	printf("-----%s------\n\n",majorDescription);    	

}    	
    }

I forgot to delete some errors. I have reposted the code. But still it doesnt read the last line

-----P0001-----

-----UG-----

-----Bachelor of Computer Science-----

-----Application Programming-----

-----BP094-----

------3----

-----FT-----

-----The Bachelor of Computer Science degrees develop a skill set that spans from theoretical and algorithmic foundations to cutting-edge developments in computing.-----

-----In this major, you will gain skills in developing practical coding solutions for the widest range of real-world problems using the latest software development skill sets.
------


-----P0002-----

-----UG-----

-----Bachelor of Computer Science-----

-----Computational Mathematics-----

-----BP094-----

------3----

-----FT-----

-----The Bachelor of Computer Science degrees develop a skill set that spans from theoretical and algorithmic foundations to cutting-edge developments in computing.-----

-----In this major, you will expand your computer science knowledge with courses in Mathematics to enable you to work in areas of computing where more complex knowledge of mathematical modelling need to be automated.
------


-----P0003-----

-----UG-----

-----Bachelor of Information Technology-----

-----Business Applications-----

-----BP162-----

------3----

-----FT-----

-----The Bachelor of Information Technology degree trains students to make a living solving, supporting, troubleshooting and designing  from web sites to business applications to programming networks.-----

-----In this major, you will be exposed to specific applications of information technology to the business world.
------


-----P0004-----

-----UG-----

-----Bachelor of Information Technology-----

-----Multimedia Design-----

-----BP162-----

------3----

-----FT-----

-----The Bachelor of Information Technology degree trains students to make a living solving, supporting, troubleshooting and designing  from web sites to business applications to programming networks.-----

----- you will focus your IT skills on the creative world of Web and Time Based Media, Narrative for Multimedia, Advanced 3D Imaging, Animation and Multimedia Authoring, etc.
------


-----P0005-----

-----PG-----

-----Master of Information Technology-----

-----N/A-----

-----MC061-----

------1----

-----FT-----

-----This program is designed for computer science graduates who want to study advanced postgraduate-level computing and gain exposure to world-class technologies.-----

-----N/A.
------


-----P0006-----

-----PG-----

-----Master of Computing-----

-----N/A-----

-----MC062-----

------3----

-----PT-----

-----The Master of Computing program is designed for non-computing graduates with good grades in their first university degree.-----

-----N/A.
------

progCode is NULL

I have used printf to output it outputs till line six when it starts to read the seventh line it prints progCode is NULL why? Fix my errors please

If you want to build a ship, don't drum up people to collect wood and don't assign them tasks and work, but rather teach them giving examples, to long for the endless immensity of the sea.

Edited 6 Years Ago by javedkhan0258: n/a

javedkhan0258> Fix my errors please
I am afraid that's something you have to do, not us. We may point to you some errors and/or show you some suggestions, but that's it.


javedkhan0258> it prints progCode is NULL why?
You must learn some more how strtok() works if you want to know. Here's a brief explanation of it. Emphasis highlighed

char * strtok ( char * str, const char * delimiters );

Split string into tokens
A sequence of calls to this function split str into tokens, which are sequences of contiguous characters separated by any of the characters that are part of delimiters.

On a first call, the function expects a C string as argument for str, whose first character is used as the starting location to scan for tokens. In subsequent calls, the function expects a null pointer and uses the position right after the end of last token as the new starting location for scanning.

To determine the beginning and the end of a token, the function first scans from the starting location for the first character not contained in delimiters (which becomes the beginning of the token). And then scans starting from this beginning of the token for the first character contained in delimiters, which becomes the end of the token.

This end of the token is automatically replaced by a null-character by the function, and the beginning of the token is returned by the function.

Once the terminating null character of str has been found in a call to strtok, all subsequent calls to this function with a null pointer as the first argument return a null pointer.

Parameters

str
C string to truncate. The contents of this string are modified and broken into smaller strings (tokens).
Alternativelly, a null pointer may be specified, in which case the function continues scanning where a previous successful call to the function ended.
delimiters
C string containing the delimiters.
These may vary from one call to another.

Return Value
A pointer to the last token found in string.
A null pointer is returned if there are no tokens left to retrieve.

Let's take a look at somethings.

} 
  	 progDuration=atoi(strtok(NULL,"|"));
	 if(progDuration==NULL){
		printf("progCode is NULL\n");
		break;
	 }

The sixth record is expected to be a string that can be converted into an integer. progDuration is an integer, right? Then if(progDuration==NULL) is incorrect, since it will be comparing an integer with a NULL. Furthermore, what's the odds that it is just below the previous call that fails?
Now, look at your supposed to be last line from the file.

P0007|UG|Bachelor of Software Engineering|BP096|4|FT|The Bachelor of Software Engineering degree is centred on the development and management of larger quality-measured software systems|N/A

The field in read is supposed to be a possible conversion to integer. What's the odds that it is the line that fails?

Certainly, you have enough information now to figure out.

By the way,

if(progId==NULL){
printf("\nprogID is NULL\n");
}

recognizes that progId could be null, however it doesn't stop the loop.
And,

progMode=strtok("|");
if(progMode==NULL){
printf("progMode is NULL\n");
break;
}

is missing the first parameter.
Posting code that will not produce the said results is an annoyance. Pay more care in accuracy.

Edited 6 Years Ago by Aia: n/a

Thanks for spending your precious time to read the whole code and explained and giving feedback. I hope you keep helping people who suffer from minor errors.

Thanks for spending your precious time to read the whole code and explained and giving feedback. I hope you keep helping people who suffer from minor errors.

You are welcome!
Concerning your statement about "minor errors", perhaps I need to impress on you the reality that in C programming the law of relativity is unrelated to us.
Consider the following excerpt from Expert C Programming: Deep C Secrets By Peter van der Linden

The $20 Million Bug
In Spring 1993, in the Operating System development group at SunSoft, we had a "priority one" bug
report come in describing a problem in the asynchronous I/O library. The bug was holding up the sale
of $20 million worth of hardware to a customer who specifically needed the library functionality, so
we were extremely motivated to find it. After some intensive debugging sessions, the problem was
finally traced to a statement that read :

x==2;
It was a typo for what was intended to be an assignment statement. The programmer 's finger had
bounced on the "equals" key, accidentally pressing it twice instead of once. The statement as written
compared x to 2, generated true or false, and discarded the result .

This article has been dead for over six months. Start a new discussion instead.