-1

如何让程序读取“partSize”字节数并将其打印到屏幕上?假设我正在打开一个总共包含 100 个字符的文本文件。如果 partSize 是 50 字节,我希望屏幕上打印 50 个字符。

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h> 
#include <sys/types.h> 
#include <errno.h>

#define PERMS 0777

int main(int argc, char *argv[])
{
    int createDescriptor;
    int openDescriptorOriginal;
    int closeCreateDescriptor;

    //char fileNameOriginal[] = "picture.jpg";
    char fileNameOriginal[] = "myFile.txt";

    int parts;
    int partSize;

    parts=2;

    int bytesRemaining;
    int partNumber;
    char BUFFER[512];
    int readDescriptor;

    if ((openDescriptorOriginal = open(fileNameOriginal, O_RDONLY )) == -1)
    {
        printf("Error opening %s", fileNameOriginal);
        exit(EXIT_FAILURE);
    }

    struct stat buf;
    int r = fstat(openDescriptorOriginal, &buf);
    if (r)
    {
        fprintf(stderr, "error: fstat: %s\n", (char *) strerror(errno));
        exit(1);
    }

    int originalFileSize = buf.st_size;
    printf("The file is %.9f Kilobytes large.\n", (double) originalFileSize/1024);

    partSize = ((originalFileSize + parts) + 1)/parts;

    //I am stuck at this part
    while ((readDescriptor = read(openDescriptorOriginal, BUFFER, partSize)) < partSize))
    {
        write(1, BUFFER, readDescriptor);
    }

    if ((closeCreateDescriptor = close(openDescriptorOriginal)) == -1)
    {
        printf("Error closing file.\n");
    }

    return 0;
}
4

1 回答 1

1

您需要检查返回值,并在每次迭代中更新长度:

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将包含读取的字节数。

于 2013-01-02T09:52:58.880 回答