Thread: help with fileio

  1. #1
    Registered User
    Join Date
    Sep 2005

    Smile help with fileio

    this is my code,,,,,,

    #include <iostream>
    #include <fstream>
    using namespace std;
    int main () {
    	int pos=50;
    	int posy;
    	ofstream out; ("fileio6.txt");
                    out.write ( "hello",pos);
    	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 int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    Because "hello" is only 5 chars, but you write out 50 ?

  3. #3
    Registered User
    Join Date
    Jan 2005
    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, 04:49 PM