File input reads in gibberish after file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <string.h>
#include <iostream>
#include <fstream>
using namespace std;

int main(int argc, char *argv[])
{
  ifstream source (argv[1], ios::in|ios::binary|ios::ate);
  int size = source.tellg();  
  char memsource[size];
  source.seekg (0, ios::beg);
  source.read (memsource, size);
  source.close();
  int filepointer = 0;
  while (filepointer < strlen(memsource) && memsource[filepointer] != 0)
  {
    cout << memsource[filepointer] << '\n';    
    filepointer++;
  }

  return 0;
 
}


For some reason this outputs the contents of the file, plus gibberish like:
���裨�u���������


Are file inputs not null terminated, or something?
I have to ask, but you are using argv[1] right? In other words you aren't just hitting run from your compiler?
opsarc wrote:
Are file inputs not null terminated, or something?

The answer is - in the case of the ifstream.read() function then NO it is not null terminated

See here:
http://www.cplusplus.com/reference/iostream/istream/read/
- Why would null termination even matter in this case? You should still get something.

- Why are you testing to see if the first array element in memsource is 0 on line 15? Is this going to be a "Don't output the file" condition? By the way you are testing an element in a char array against an 'int' they will never be equal IIRC.

I think you are getting ahead of your self, simplify the code. When you get it working at a lower level then implement what you are trying to do one step at a time.
Topic archived. No new replies allowed.