Still cant print text file in console window

If I run this code it simply crashes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/* fread example: read a complete file */
#include <stdio.h>
#include <stdlib.h>

int main () {
  FILE * pFile;
  long lSize;
  char * buffer;
  size_t result;

  pFile = fopen ( "file.txt" , "rb" );
  if (pFile==NULL) {fputs ("File error",stderr); exit (1);}

  // obtain file size:
  fseek (pFile , 0 , SEEK_END);
  lSize = ftell (pFile);
  rewind (pFile);

  // allocate memory to contain the whole file:
  buffer = (char*) malloc (sizeof(char)*lSize);
  if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}

  // copy the file into the buffer:
  result = fread (buffer,1,lSize,pFile);
  if (result != lSize) {fputs ("Reading error",stderr); exit (3);}
  printf("%s",result);

  /* the whole file is now loaded in the memory buffer. */

  // terminate
  fclose (pFile);
  free (buffer);
  return 0
I haven't tried this to verify it, but I don't think you are allowing for the terminating NULL, so try this...

buffer=(char*)malloc(sizeof(char*)*lSize +1);

I think you have to have the * in your sizeof() operator, but if the above doesn't work, remove that and try again.

Last edited on
Hi,
I just tried your code with Open Watcom, ( my preferred compiler ), and it gave me numerous warings! As advised, your malloc etc is wrong for the context you want.
I chaged it to give a file size and lo and behold - no probs.
Often we see people using 'compilers' like VC++ Epresss and the others. Why not use a 'real' compiler. Watcom is free, ( and has everything for Microsoft users ). Lets face it, if you're going to write serious sofware then you need to use professional tools.

>> Lets face it, if you're going to write serious
>> sofware then you need to use professional tools.

Let's face it, a professional programmer would have never had that problem in the first place.
Very good Lamblion - tonight I can't see the wood for the trees again!
I was was going to ask you for a discussion sometime but I'm exhausted tonight and that bit of grey matter that I might have left, well its gone - so I'm off to bed - Goodnight.
Topic archived. No new replies allowed.