c++ - C 创建一个给定大小的文件

标签 c++ c linux

我正在尝试使用 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/

相关文章:

C++ 在 Xcode 控制台中不显示 cout 但在终端中运行完美

c - 理解 if (a>=3) 的 gcc 输出

c - C : is it guaranteed to return 0/1? 中的双重否定

c - 提升指向未定义位置的指针是否合法?

linux - Gadwin 打印屏幕的替代品

c++ - std::plus 的模板推导失败

C++,对象 vector

c++ - 将图像文件 (.bmp) 复制到其他位置

linux - 正在运行的进程上的 greps 管道不输出任何内容

Linux 上的 Java BlockingQueue 延迟高