reading from file
Posted on 2003-03-16
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";
printf("Enter name of source file\n");
printf("Enter name of output file\n");
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.