Thread: File I/O Question

  1. #1
    Registered User
    Join Date
    Oct 2005
    Posts
    17

    File I/O Question

    I'm trying to write a program to format a text file and I can't figure out how to write to the file passed in the command line.

    Here is what I have tried in pseudocode:
    -open the file argv[1] for reading
    -open my temporary file for writing
    -read a line of the original file into a buffer via "fgets"
    -format it accordingly
    -put the newly formatted line into the temp file via "fputs"
    -do the previous 3 steps until the original file ends
    -close both files via "fclose"
    -remove the original file via "remove"
    -rename the temp file to the original file via "rename"

    This isn't working (Seg Fault) I think because it is not able to delete the file contained in the command line (argv[1]). I have tested, and the temporary file is getting the data successfully--the problem lies in the transferring of the contents of the temporary file to the original file (or at least renaming the temp file to the original). I tried other methods of transferring the data, but they all return a Seg Fault.

    Am I going about this all wrong? Or is there a trick to manipulating files included in the command line?

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Do you check the values returned by remove and rename? And some of the other functions? When you "format it accordingly" do you wander off the buffer?

    Perhaps strip some things out to narrow down the bug search.

    [edit]Do you malloc some memory and lose the pointer and then try to free it?
    Last edited by Dave_Sinkula; 11-17-2005 at 11:52 PM.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    Registered User
    Join Date
    Oct 2005
    Posts
    17
    I totally forgot to malloc my buffer >.< that did it. 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. File i/o and ASCII question
    By muzihc in forum C Programming
    Replies: 13
    Last Post: 11-04-2008, 11:46 PM
  3. Inventory records
    By jsbeckton in forum C Programming
    Replies: 23
    Last Post: 06-28-2007, 04:14 AM
  4. Very quick question about File I/O
    By homegrown in forum C++ Programming
    Replies: 5
    Last Post: 09-09-2003, 09:08 PM
  5. Another dumb question about file i/o
    By Cobras2 in forum C++ Programming
    Replies: 23
    Last Post: 03-14-2002, 04:15 PM