c - 如何跟踪执行了多少读/写操作...?

标签 c file-io buffer read-write

对于我的类(class),“开发一个 C 程序,将输入文件复制到输出文件并计算读/写操作的数量。”我知道如何执行将输入文件复制到输出文件的操作,但我不完全确定如何跟踪执行了多少次读/写操作。该程序应该使用不同的缓冲区大小重复复制,并输出使用每个缓冲区大小执行的读/写操作数量的列表。我只是不确定如何执行计算读/写操作的部分。怎么可能去做这件事呢?预先感谢您。

这是我当前的代码(已更新):

#include <stdio.h>
#include "apue.h"
#include <fcntl.h>

#define BUFFSIZE 1

int main(void)
{
    int n;
    char buf[BUFFSIZE];
    int input_file;
    int output_file;
    int readCount = 0;
    int writeCount = 0;

    input_file = open("test.txt", O_RDONLY);
    if(input_file < 0)
    {
        printf("could not open file.\n");
    }

    output_file = creat("output.txt", FILE_MODE);

    if(output_file < 0)
    {
        printf("error with output file.\n");
    }


    while((n = read(input_file, buf, BUFFSIZE)) > 0)
    {
        readCount++;
        if(write(output_file, buf, n) == n){
            writeCount++;
        }else{
            printf("Error writing");
        }
    }

    if(n < 0)
    {
        printf("reading error");
    }

    printf("read/write count: %d\n", writeCount + readCount);
    printf("read = %d\n", readCount);
    printf("write = %d\n", writeCount);

}

对于文本文件:测试一二

结果是:

read/write count: 26
read = 13
write = 13

Process returned 0 (0x0)   execution time : 0.003 s
Press ENTER to continue.

我以为写入会是 12...但我不确定...

最佳答案

每次调用执行读取或写入操作的函数时,都需要递增变量。您可以通过创建一个包装标准 i/o 函数的函数来实现这一点。

例如,将 fread 替换为如下内容:

size_t fread_count(void *p, size_t size, size_t num, FILE *f){
    iocount++;
    return fread(p, size, num, f);
}

iocount 必须在范围内(例如全局)

如果需要单独计算读取和写入次数,请使用单独的变量。 一种是在读取时递增,另一种是在写入时递增。 -编辑- 由于您正在使用 write() 和 read(),因此您可以轻松地制作等效的 功能与上面类似,但使用 write 和 read 而不是 fwrite 和 fread

关于c - 如何跟踪执行了多少读/写操作...?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29038986/

相关文章:

linux - linux 套接字内核缓冲区是否交换到磁盘?

python - GzipFile 中的缓冲

c++ - libevent bufferevent 的 evbuffer_add

c - 如何制作一个空指针来读取二进制文件的给定部分

c - 如何使用 Arduino - atmega 2560 微 Controller 实现 8 位 DAC(数模转换)?

c - 在 C 中使用可变参数函数进行字符串连接

c# - 如何有效地使用内存附加到 C# 中的大型 XML 文件

java - 写入文件而不删除当前数据

计算 malloc() 和 realloc() 大小的正确方法?

javascript - 如何在没有提示的情况下在 Google Chrome App 中写入文件?