write into file

This is a discussion on write into file within the C Programming forums, part of the General Programming Boards category; I have problems writing into a file. example: I have a file name abc.txt and i want to write/append a ...

  1. #1
    Registered User
    Join Date
    Mar 2010
    Location
    Singapore
    Posts
    11

    write into file

    I have problems writing into a file.

    example: I have a file name abc.txt and i want to write/append a character to the end of the file. However, it is written to the next line.

    before write:
    abc

    after write:
    abc
    H

    what i want:
    abcH

    here is my code:
    Code:
    int main ( int argc, char ** argv ) {
    	char *fileName = argv[1];
    	int fd;
    	fd = open(fileName, O_RDWR ,0666);
    	lseek(fd,0,SEEK_END);
    	char test[1];
    	test[0] = 'H';
    	write(fd,&test,sizeof(test));
    return 0;
    }
    Something wrong with my code?
    Thanks in advance!

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,506
    Well what you get really depends on what is at the end of the file.

    To do what you ask, you would need to seek to the end, then step back a character or two, then write your data AND a replacement newline.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    cas
    cas is offline
    Registered User
    Join Date
    Sep 2007
    Posts
    982
    Have you verified that there is not a newline at the end of the file? If you created it with a text editor, there probably is one. If there's a newline, the new character will be written after it.

    Incidentally, there is no need to provide a mode to open() if you're not passing O_CREAT.

  4. #4
    Registered User
    Join Date
    Mar 2010
    Location
    Singapore
    Posts
    11
    Thanks!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A development process
    By Noir in forum C Programming
    Replies: 37
    Last Post: 07-10-2011, 10:39 PM
  2. help with text input
    By Alphawaves in forum C Programming
    Replies: 8
    Last Post: 04-08-2007, 04:54 PM
  3. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 01:53 AM
  4. Encryption program
    By zeiffelz in forum C Programming
    Replies: 1
    Last Post: 06-15-2005, 03:39 AM
  5. archive format
    By Nor in forum A Brief History of Cprogramming.com
    Replies: 0
    Last Post: 08-05-2003, 07:01 PM

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