我在 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 之外完全相同的程序。
EINVAL
fd
is attached to an object which is unsuitable for writing; or the file was opened with theO_DIRECT
flag, and either the address specified inbuf
, the value specified incount
, or the file offset is not suitably aligned.
除非您知道自己在做什么以及为什么,否则不要使用O_DIRECT
。去掉它。并阅读文档!
关于c - 程序不将数组写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52945368/