开发者

lseek() returning 0 when followed by new open()

开发者 https://www.devze.com 2022-12-16 12:01 出处:网络
I have the following bit of code (it\'s \"example\" code, so nothing fancy): #include <stdio.h> #include <string.h>

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?


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;


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号