Not what I expected


Results 1 to 4 of 4

Thread: Not what I expected

  1. #1
    Join Date
    Oct 2003
    Posts
    49

    Not what I expected

    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");

    }

  2. #2
    Join Date
    Sep 2002
    Posts
    766
    using the buffer is kind of pointless unless you want to write the buffer out that way....
    could just

    Code:
    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
    Code:
    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;
    }

  3. #3
    Join Date
    Oct 2003
    Posts
    49
    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.

  4. #4
    Join Date
    May 2001
    Location
    Uh, I'm somewhere where I don't know where I am.
    Posts
    1,228

    Re: Not what I expected

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

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

    Parens are your friend!!
    if (i_forgot && this_is_about_code)
    language = c++;

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •