C 程序不将数组写入文件

C 程序不将数组写入文件,c,C,我在Ubuntu上无法写入文件。我想创建4MB大小的文件,因此我将写入大小为4096字节的1024个块。程序在桌面上创建一个文件,但当我打开它时,它是空的,大小为0字节。文件可以打开,写入返回值-1。errno表示参数无效 代码: float timedifference_msec(struct timeval t0,struct timeval t1) { 返回(t1.tv_-sec-t0.tv_-sec)*1000.0f+(t1.tv_-usec-t0.tv_-usec)/1000.0f;

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

代码:

float timedifference_msec(struct timeval t0,struct timeval t1)
{
返回(t1.tv_-sec-t0.tv_-sec)*1000.0f+(t1.tv_-usec-t0.tv_-usec)/1000.0f;
}
内部主(空)
{
结构时间值t0,t1;
浮子过去了;
struct timespec start1,end1;
字符c_数组[4096];
int i=0;
int j=0;
int fdw=open(“/home/user/Desktop/xxxy.txt”,O|u CREAT | O|u WRONLY | O|u DIRECT,0644);

对于(i=0;i好的,那么您说
write
调用失败,错误号为“Invalid argument”,即
EINVAL
。在发布的代码中,您实际上没有观察到这一点,但为了参数起见,假设您实际运行的程序与检查错误号不同

清楚地说:

EINVAL
fd
附加到不适合写入的对象;或者文件是使用
O_DIRECT
标志打开的,并且
buf
中指定的地址、
count
中指定的值或者文件偏移量没有适当对齐


不要使用
O_DIRECT
,除非您知道自己在做什么以及为什么要这样做。将其删除。然后阅读文档!

您没有检查您的
write()<代码> >调用任何错误-你只是假设它是有效的。为什么你不使用“代码> fcx//Cuthor?文件描述符不会结束……使用<代码>关闭<代码>。你写C还是C++?这是令人困惑的。而且,是的,使用FSULTS!@多数如果代码“写/代码>返回1,将包含一个错误代码,它会告诉你为什么<代码> WR。ite
已失败。是否有其他解决方案如何使用O_DIRECT打开文件并写入文件?我需要O_DIRECT标志以最小化缓存效果。@大多数人阅读,特别是
O_DIRECT
相关内容和/或google
O_DIRECT
@maist为什么你认为需要最小化缓存效果?我需要测量延迟在CPU和磁盘之间。所以实际上,这个问题是关于如何在这种情况下正确使用
O_DIRECT
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;
} 
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);