Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Two part question. Modifying a file with C++ on Unix

Status
Not open for further replies.

menace212

Programmer
Jul 11, 2003
144
US
How do I write a function to modify a file in Unix where I created a newfile and I'm attempting to add char's to the file, but when I add the char's it appends it on the same line. I want it to go to the next line and add then next line and add. Example below:

wrong:What I don't want it to do
/bin/sh/bin/ksh/bin/csh

right:What I want it to do
/bin/sh
/bin/ksh
/bin/csh

Program Function:

fd = creat("/etc/shells", 0755);
f_write = fopen("/etc/shells", "a+");

fputs("/bin/sh", f_write);
fputs("/bin/csh", f-write);
fputs("/bin/ksh", f_write);

Second Question:

I want to append char's on a line where I can add to the end of it. Example

before:
ftp inet

after:
ftp inet +1 -U
 
write the following

fputs("/bin/sh\n", f_write);
fputs("/bin/csh\n", f-write);
fputs("/bin/ksh\n", f_write);


For second question...

You will not be able to edit file in between... You will have to read from one file add some more things and write to second file..
 
thanks g...Hey What command can I use to append it then write the entire string in it's place. Because if I use putc('char', f_write) I'll get an error stating the char was too long?
 
Well there are multiple ways of doing it.. One is what you are saying of writing char by char in the output file. But that will be inefficient.
You can prepare your string first and then write the complete string in one go..
Say File 1 :-

ftp inet

Say you read this string from the file using
char buf[100];

fgets(buf)

Now buf will contain "ftp inet"

Now you can sprintf(buf,"%s%s",buf,"NEW STRING HERE");

fwrite(buf)


I hope this helps.

 
How about putc('cccc',f) error "char too long"? Is it compiler error? Do you write literally putc('c...'? Then it's erroneous multi-byte char constant, that's all.
It doesn't matter how to write bytes to file: by putc or by fwrite (in this context).
It seems menace212 pay not attention to gasingh's note about an impossibility to expand or truncate file in place (Am I wrong?). That suspicious game with add-append-string-in-place terms...
It's possible it's time to come back and to define the issue more precisely. Sorry.
 
Thanks fellas I gotta it. I use a while loop and if/else statment to erase the line and type in the new one..thanks
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top