代码之家  ›  专栏  ›  技术社区  ›  Christian P.

lseek()后面跟着new open()时返回0

  •  0
  • Christian P.  · 技术社区  · 15 年前

    我有以下代码(它是“示例”代码,所以没有什么特别之处):

    #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);
        }
    }
    

    此代码不会按原样返回第一个打印输出(读取),第二个打印输出为:“write test.txt 0 characters from current(0):”,表示它没有在文件中查找任何位置,缓冲区为空。

    奇怪的是,如果我从 fp2 = open("test.txt", O_WRONLY); ,第一个打印输出返回我期望的结果。只要我包括第二个 open 声明(即使没有其他内容)也写不出来。它是以某种方式重新排序公开声明还是其他什么?

    2 回复  |  直到 15 年前
        1
  •  5
  •   nos    15 年前

    线

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

    是错误的,您正在获取未初始化缓冲区的strlen。您可能希望缓冲区的大小如下所示:

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

    当您将缓冲区作为一个字符串打印时,您应该确保缓冲区确实包含以nul结尾的字符串。

    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;
    
        2
  •  0
  •   bmargulies    15 年前

    你确定每次运行时都要清除文件吗?

    如前所述,第一次运行此程序时,只会看到第二次打印输出,第二次可能会看到第一次打印输出。