C创建一个给定大小的文件 [英] C creating a file with given size

查看:179
本文介绍了C创建一个给定大小的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用lseek()创建一个给定大小的文件,并在文件的末尾添加一个字节,但它创建一个0字节的稀疏文件。

I am trying to create a file with a given size using lseek() and adding a byte at the end of the file, however it creates a sparse file with 0 byte.

以下是代码...任何建议?

Below is the code...any suggestions?

#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;
}

没有大括号,如果语句是 printf ,并且 return 1; 语句总是运行 inputFd 的值是什么。

Without the braces, the only statement controlled by the if statement is the printf, and the return 1; statement is always run no matter what the value of inputFd is.

这是一个很好的做法,总是使用大括号即使只有一个语句(例如在程序结尾的 close )。

It is good practice to always use braces around a controlled block, even if there is only one statement (such as for the close at the end of your program).

这篇关于C创建一个给定大小的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆