Link to home
Start Free TrialLog in
Avatar of CaptainSparky
CaptainSparky

asked on

reading from file

I'm a 3rd year computer science student who is new to C programming and needs some help.

I can get this program to write to a file without any problems, but whenever I try to read from the file it comes back null.

Here's my code:

char *string="My dog has fleas";
char *ptr,*input[50],*output[50];
int count=1;

int main()
{

FILE *in;
FILE *out;

printf("Enter name of source file\n");
scanf("%s",&input);
printf("Enter name of output file\n");
scanf("%s",&output);

in = fopen(source,"r");        //assigns the source file to 'in' for read only
out = fopen(output,"w+");      //assigns the output file to 'out' for writing/overwriting

fputs(string,out);             //outputs the value of string to the file

fread(ptr,sizeof(*string),count,in);     //reads the file and assigns what is read to ptr
                                                                                //count is the number of characters to read
printf("%s\n",ptr);                     //prints the ptr string.

}

Interestingly, the fread() function returns 0, so it is working.  I just cant figure out why ptr is NULL in the printf() statement.  It should be equal to the first character in string (ie: "M"). My understanding is that it should be null in the fread() statement.

Unfortunately my Systems Programming teacher doesn't consider teaching to be one of his job functions, so any help is greatly appreciated.
Avatar of CaptainSparky
CaptainSparky

ASKER

Sorry folks, but I've solved my own question.
The solution was simply to point *ptr to *string
(ie: ptr=string;)

That one simple line did the trick.
ASKER CERTIFIED SOLUTION
Avatar of efn
efn

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
Thanks very much for the suggestion.  I tried it and it works.