Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

c - read() only reads a few bytes from file

I wanted to read the content of a file using the read() function. I tried the following:

#define BUFFER_LENGTH (1024)

char buffer[BUFFER_LENGTH];

// The first version of the question had a typo:
// void read_file(const char filename)
// This would produce a compiler warning.
void read_file(const char *filename)
{
    ssize_t read_bytes = 0;

    // The first version had the mode in hex instead of octal.
    //
    //     int fd_in = open(filename, O_RDONLY, 0x00644);
    //
    // This does not cause problems here but it is wrong.
    // The mode is now octal (even if it is not needed).
    int fd_in = open(filename, O_RDONLY, 0644);
    if (fd_in == -1)
    {
        return;
    }

    do
    {
        read_bytes = read(fd_in, buffer, (size_t) BUFFER_LENGTH);
        printf("Read %d bytes
", read_bytes);

        // End of file or error.
        if (read_bytes <= 0)
        {
            break;
        }
    } while (1);

    close(fd_in);
}

I am using 'gcc (GCC) 3.4.2 (mingw-special)' on a Windows 7 system.

The strange behaviour I get is that not all the content is read. For example, I have a file

05.01.2012  12:28            15.838 hello.exe

and when I try to read it I get:

Read 216 bytes
Read 0 bytes

As far as I know read() should keep reading until it reaches the end of the file. While does it report an end of file (0) the second time it is called?

Maybe I am missing something obvious but I cannot see it. I have read this document and this document over and over again and I cannot find what I am doing wrong. Does anyone have any clue?

EDIT

Thanks for the hint! It is a typo in the question (I have corrected it). It is correct in the source code.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I suspect byte 217 to be EOF (26, 0x1A) - in Windows files can be opened in "text" or "binary" mode. In text mode, a 0x1A is interpreted as EOF.

You would need to look at your open mode - O_BINARY. In PHP this is why you must fopen with mode "rb" (READ BINARY) and not "R" ("R" which defaults to READ TEXT).

http://www.mingw.org/wiki/FAQ says the flag is O_BINARY (near bottom of page), so you'd need

int fd_in = open(filename, O_RDONLY | O_BINARY, 0644);

http://cygwin.com/faq.html paragraph 5.3 tells you how to handle this in cygwin


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...