help with fileio

This is a discussion on help with fileio within the C++ Programming forums, part of the General Programming Boards category; this is my code,,,,,, Code: #include <iostream> #include <fstream> using namespace std; int main () { int pos=50; int posy; ...

  1. #1
    Registered User
    Join Date
    Sep 2005
    Posts
    142

    Smile help with fileio

    this is my code,,,,,,

    Code:
    #include <iostream>
    #include <fstream>
    
    using namespace std;
    
    int main () {
    
    	int pos=50;
    	int posy;
    
    	ofstream out;
    	out.open ("fileio6.txt");
                    
                    out.write ( "hello",pos);
    
    	pos=out.tellp();
    
    	cout<< pos;
    
    }
    now it seems to do the job i want but when i check th text file this is what i get on the top line, i was ecpecting the hello but i don't know hy the rest is there.

    hello fileio5.txt x@ X 

    if you could tell me why i would appreciate it llllloooooooootts
    WhAtHA hell Is GoInG ON

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,548
    Because "hello" is only 5 chars, but you write out 50 ?

  3. #3
    Registered User
    Join Date
    Jan 2005
    Posts
    7,319
    write() doesn't pay attention to what you are trying to write out, it just does it for you (since it is meant for binary output). So it doesn't know that you want it to stop when the terminating null character and the end of the character array is reached, it just thinks that it is supposed to write out 50 characters starting at the first character of the literal "hello". Everything after the first 6 is junk stuck in memory. (Notice that the literal "fileio6.txt" is also in memory around the same place as "hello".)

    Assuming you don't want binary, use operator<< to write out your string. If you do want binary, then only write out the number of characters you want to write out.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with FileIO
    By iiwhitexb0iii in forum C Programming
    Replies: 12
    Last Post: 04-03-2006, 11:11 AM
  2. Replies: 13
    Last Post: 03-07-2005, 03:49 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21