Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 165
  • Last Modified:

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");
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.
  • 2
1 Solution
CaptainSparkyAuthor Commented:
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.
That solution may work, but it could probably be improved.

If the "ptr=string" assignment occurred before the call to fread, you are using the string constant named "string" as an input buffer.  That is, you are telling fread to write over it.  This is not a good idea.  In the words of Harbison and Steele, "You should never attempt to modify the memory that holds the characters of a string constant, since that memory may be 'read-only,' that is, physically protected against modification."  (_C:  A Reference Manual_, 4th ed., 1995, p.31).

The usual approach is to use a character array:

char inputbuffer[500];

fread(inputbuffer, size, count, stream);

CaptainSparkyAuthor Commented:
Thanks very much for the suggestion.  I tried it and it works.

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now