C programming print a certain amount of bytes to screen

前端 未结 1 603
盖世英雄少女心
盖世英雄少女心 2020-12-22 14:41

How can I make the program read \"partSize\" amount of bytes and print it to the screen? Let\'s say that I am opening a text file that contains 100 characters in total. If p

相关标签:
1条回答
  • 2020-12-22 15:03

    You need to check the return value, and update the length in each iteration:

    ssize_t count, total;
    total = 0;
    char *buf = BUFFER;
    while (partSize) {
        count = read(openDescriptorOriginal, buf, partSize);
        if (count < 0) {
            /* handle error */
            break;
        }
        if (count == 0)
            break;
        buf += count;
        total += count;
        partSize -= count;
    }
    write (1, BUFFER, total);
    

    total will contain the number of bytes read.

    0 讨论(0)
提交回复
热议问题