c - 程序不将数组写入文件

标签 c

我在 Ubuntu 上写入文件时遇到问题。我想创建大小为 4MB 的文件,因此我将写入 1024 个大小为 4096 字节的 block 。程序在桌面上创建一个文件,但是当我打开它时,它是空的,大小为 0 字节。文件可以打开,写入返回值-1。 errno 表示参数无效。

代码:

float timedifference_msec(struct timeval t0, struct timeval t1)
{
    return (t1.tv_sec - t0.tv_sec) * 1000.0f + (t1.tv_usec - t0.tv_usec) / 1000.0f;
}

int main(void)
{
    struct timeval t0, t1;
    float elapsed;
    struct timespec start1, end1;
    char c_array [4096];
    int i = 0;
    int j = 0;

    int fdw = open("/home/user/Desktop/xxxy.txt", O_CREAT |O_WRONLY |O_DIRECT, 0644);

    for(i=0; i<4096; i++){
        c_array[i] = '0';
    }

    for(j=0; j<1024; j++){
        gettimeofday(&t0, 0);
        unsigned long start =
            std::chrono::duration_cast<std::chrono::milliseconds>
            (std::chrono::system_clock::now().time_since_epoch()).count();

        write(fdw, c_array, 4096);
        fsync(fdw);
        gettimeofday(&t1, 0);
        unsigned long end =
            std::chrono::duration_cast<std::chrono::milliseconds>
            (std::chrono::system_clock::now().time_since_epoch()).count();
        elapsed = timedifference_msec(t0, t1);
        printf("%d - Elapsed time: %f : %f\n", j, elapsed, end-start);
    }

    close(fdw);

    return 0;
} 

//O_DIRECT方法

void *buf;
posix_memalign(&buf, 4096, 4096);

int fdw = open("/home/user/Desktop/xx1.txt", O_CREAT |O_WRONLY| O_TRUNC|O_DIRECT, S_IRWXU);     
for(i=0; i<4096; i++){
    c_array[i] = '9';
} 

memcpy(buf, c_array, sizeof(c_array)); 

for(i=0; i<512; i++){
    gettimeofday(&t0, 0);     
    write(fdw, buf, 4096);
    fsync(fdw);   
    gettimeofday(&t1, 0);    
    elapsed = timedifference_msec(t0, t1);    
    printf("%3d - Elapsed time: %f milliseconds.\n", i, elapsed);     
} 

close(fdw);
free(buf);

最佳答案

好的,所以你说 write 调用失败,错误号为“无效参数”,即 EINVAL。在发布的代码中,您实际上并没有观察到这一点,但为了论证起见,我们假设您实际上正在运行一个除了检查 errno 之外完全相同的程序。

The manpage for write明确表示:

EINVAL
fd is attached to an object which is unsuitable for writing; or the file was opened with the O_DIRECT flag, and either the address specified in buf, the value specified in count, or the file offset is not suitably aligned.

除非您知道自己在做什么以及为什么,否则不要使用O_DIRECT。去掉它。并阅读文档!

关于c - 程序不将数组写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52945368/

相关文章:

c - 如何将 C 指针递增 2

calloc() 指向结构中的指针在 clang 上不起作用

c - 地址的数据大小

c - gcc 和 g++ 编译器创建的 C 程序可执行文件之间的性能差异

c - 阿尔萨 API : How to play two wave files simultaneously?

c - 如何使用 C 程序在命令提示符下传递命令?

我可以在 c 语言中将 fscanf 与二进制文件一起使用吗?

c - C语言从String中读取数据

android - 在android ndk中使用bool变量时出错

c++ - 如何使用Windows api中的参数执行线程?