tags:

views:

104

answers:

2

I have the following bit of code (it's "example" code, so nothing fancy):

#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
    char buffer[9];
    int fp = open("test.txt", O_RDONLY);

    if (fp != -1) // If file opened successfully
    {
        off_t offset = lseek(fp, 2, SEEK_SET); // Seek from start of file
        ssize_t count = read(fp, buffer, strlen(buffer));
        if (count > 0) // No errors (-1) and at least one byte (not 0) was read
        {
            printf("Read test.txt %d characters from start: %s\n", offset, buffer);
        }

        close(fp);
    }

    int fp2 = open("test.txt", O_WRONLY);
    if (fp2 != -1)
    {
        off_t offset = lseek(fp2, 2, SEEK_CUR); // Seek fraom current position (0) - same result as above in this case
        ssize_t count = write(fp2, buffer, strlen(buffer));
        if (count == strlen(buffer)) // We successfully wrote all the bytes
        {
             printf("Wrote to test.txt %d characters from current (0): %s\n", offset, buffer);
        }

        close(fp2);
    }
}

This code does not return the first printout (reading) as it is, and the second printout reads: "Wrote test.txt 0 characters from current (0): " indicating that it did not seek anywhere in the file and that buffer is empty.

The odd thing is, if I comment out everything from fp2 = open("test.txt", O_WRONLY);, the first printout returns what I expected. As soon as I include the second open statement (even with nothing else) it won't write it. Does it somehow re-order the open statements or something else?

+5  A: 

The line

ssize_t count = read(fp, buffer, strlen(buffer));

is wrong, you're taking the strlen of an uninitialized buffer. You likely want the size of the buffer like so:

ssize_t count = read(fp, buffer, sizeof buffer);

You should make sure buffer really contain a nul terminated string as well when you print it as one.

if (fp != -1) // If file opened successfully
{

    off_t offset = lseek(fp, 2, SEEK_SET); // Seek from start of file
    ssize_t count = read(fp, buffer, sizeof buffer - 1);
    if (count > 0) // No errors (-1) and at least one byte (not 0) was read
    { 
       buffer[count] = 0;
nos
Seems to be working. It seems that in some instances of the program, buffer would be filled with garbage at start, making it work, and sometimes it wasn't (in this particular case). Me and memory...
Christian P.
`buffer`, being an automatic variable, is not initialized to `0`, so it contains random values. If `buffer` was `static` or "global", it would be initialized to all bytes 0.
Alok
A: 

Are you perfectly sure you are cleaning out the file every time you run?

As written, the first time you run this, you'll only see the second printout, and the second time you might see the first one.

bmargulies