Click to See Complete Forum and Search --> : Not what I expected


bsamuels
10-26-2003, 11:35 PM
This simple routine to create a new file and write a short entry, doesn't do what I expected. On running it, the character string that is supposedly written is output to the screen and nothing seems to be written to the file. (The . designation is for a purpose)

void create_file()
{
int out_fd, n_chars,i,len;
char buf[BUFFERSIZE];
char * b = "logmesg: ";
len = strlen(b) ;


for( i =0;i < len;i++)
buf[i] = * b++;
buf[len] = '\0';

if ( out_fd = open("/home/Bruce/.logmesg",O_CREAT|O_RDWR|O_TRUNC, 0666 )== -1 )
perror("Cannot open logmesg");

if ( write( out_fd, buf, len ) != len)
oops("Write error ","");

if (close(out_fd) == -1 )
perror("Error closing files");

}

GaryJones32
10-27-2003, 01:15 AM
using the buffer is kind of pointless unless you want to write the buffer out that way....
could just


int out_fd;
char * filename = "/home/Bruce/.logmesg";
char * b = "logmesg: ";
// len has to be size_t not int
size_t len = strlen(b);
// might want APPEND for a log message
if ( out_fd = open(filename,O_WRONLY|O_CREAT|O_APPEND, 0666 )== -1 )
perror("Cannot open logmesg");
write(out_fd,b,len);
close(out_fd);


to write out a buffer in a loop

ssize_t write_out(int fd , const void * buffer, size_t count) {
size_t still_left = count;
while (still_left > 0) {
size_t written = write(fd,buffer,count);
if (written == -1)
return -1;
else
still_left -= written;
}
assert (still_left == 0);
return count;
}

bsamuels
10-27-2003, 11:04 AM
Thanks, but that still doesn't do as I expect, It prints to the screen without writing to the file. I don't understand that.

tecknophreak
10-27-2003, 11:51 AM
if ( out_fd = open("/home/Bruce/.logmesg",O_CREAT|O_RDWR|O_TRUNC, 0666 )== -1 )


Fix:
if ( (out_fd = open("/home/Bruce/.logmesg",O_CREAT|O_RDWR|O_TRUNC, 0666 ))== -1 )

Parens are your friend!! :cool: