Link to home
Start Free TrialLog in
Avatar of homerz
homerz

asked on

Reading from a file.

Can someone show me the code that does the following simple task:
a program that reads the number on the last line from a file "junk.txt", increments that number and stores the result on a new line at the bottom of the file. (let's assume that the file initially contains one line with the number "0").
Thanks.
ASKER CERTIFIED SOLUTION
Avatar of Kent Olsen
Kent Olsen
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
please clarify your question, are u just readind one number from file then writing the new value to a new line?

if so, then here's an example:

/*Assuming file already exists*/
/* First open file */
fptr=fopen("junk.txt","r+");

/*Asuming the contains integer character*/
/*Read value from last line*/
do
{
   fscanf(fptr,"%d",value);
}
while(!feof);

/*Write new value to file in new line*/
fprintf(fptr,"\n%d",value);

/*This is just a code sample, you will need to do the rest.
I cannot give you the entire code.
you will need to create a loop to control the function
if you plan to read and write more than one value.*/

mkandre
Avatar of homerz
homerz

ASKER

Ok first of all thanks for ur help.
I did write a code and everything is working just fine except that im not able to write to the file.
The problem is as follows: lets say i have the following:
FILE *fp;
fp= open("fgetsc.txt","r");
char test= '1';

Now i want to add the character "test" on a new line in the file that initially contains let's say one character on the first line. How can i do that?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial