我正在尝试使用 lseek() 创建一个给定大小的文件并在文件末尾添加一个字节,但是它创建了一个 0 字节的稀疏文件。
下面是代码...有什么建议吗?
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#ifndef BUF_SIZE
#define BUF_SIZE 1024
#endif // BUF_SIZE
int main(int argc, char *argv[])
{
int inputFd;
int fileSize = 500000000;
int openFlags;
int result;
mode_t filePerms;
ssize_t numRead;
char buf[BUF_SIZE];
openFlags = O_WRONLY | O_CREAT | O_EXCL;
filePerms = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH; /*rw-rw-ew*/
inputFd = open(argv[1], openFlags, filePerms);
if (inputFd == -1)
printf("problem opening file %s ", argv[1]);
return 1;
printf ("input FD: %d", inputFd);
result = lseek(inputFd, fileSize-1, SEEK_SET);
if (result == -1){
close(inputFd);
printf("Error calling lseek() to stretch the file");
return 1;
}
result = write(inputFd, "", 1);
if (result < 0){
close(inputFd);
printf("Error writing a byte at the end of file\n");
return 1;
}
if (close(inputFd) == -1)
printf("problem closing file %s \n",argv[1]);
return 0;
}
最佳答案
您缺少一些牙套:
if (inputFd == -1)
printf("problem opening file %s ", argv[1]);
return 1;
您需要将其更改为:
if (inputFd == -1) {
printf("problem opening file %s ", argv[1]);
return 1;
}
没有大括号,if
语句控制的唯一语句是printf
,而return 1;
语句始终运行 no无论 inputFd
的值是多少。
最好始终在受控 block 周围使用大括号,即使只有一条语句(例如程序末尾的close
)也是如此.
关于c++ - C 创建一个给定大小的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27714834/