在UNIX环境中使用C编程语言创建空文件时遇到问题

时间:2016-02-26 16:54:49

标签: unix systems-programming

我最近在UNIX环境中开始编程。我需要编写一个程序,使用这个命令创建一个空文件,其名称和大小在终端中给出

gcc foo.c -o foo.o 
./foo.o result.txt 1000

这里result.txt表示新创建的文件的名称,1000表示文件的大小(以字节为单位)。

我确定 lseek 函数会移动文件偏移量,但问题是每当我运行程序时它会创建一个具有给定名称的文件,但是文件的大小是 0

这是我的小程序的代码。

#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/stat.h>
int main(int  argc, char **argv)
{
    int fd;
    char *file_name;
    off_t bytes;
    mode_t mode;

    if (argc < 3)
    {
        perror("There is not enough command-line arguments.");
        //return 1;
    }

    file_name = argv[1];
    bytes = atoi(argv[2]);
    mode = S_IWUSR | S_IWGRP | S_IWOTH;

    if ((fd = creat(file_name, mode)) < 0)
    {
        perror("File creation error.");
        //return 1;
    }
    if (lseek(fd, bytes, SEEK_SET) == -1)
    {
        perror("Lseek function error.");
        //return 1;
    }
    close(fd);
    return 0;
}

1 个答案:

答案 0 :(得分:0)

如果您不允许使用任何其他功能来帮助创建“空白”文本文件,为什么不在creat上更改文件模式,然后循环写入:

int fd = creat(file_name, 0666);

for (int i=0; i < bytes; i++) {
    int wbytes = write(fd, " ", 1);
    if (wbytes < 0) {
        perror("write error")
        return 1;
    }
}

你会想要在这里进行一些额外的检查,但这是一般的想法。

我不知道您的情况可以接受,但可能只在write之后添加lseek来电:

if ((fd = creat(file_name, 0666)) < 0) // XXX edit to include write
{
    perror("File creation error.");
    //return 1;
}
if (lseek(fd, bytes - 1, SEEK_SET) == -1) // XXX seek to bytes - 1
{
    perror("Lseek function error.");
    //return 1;
}

// add this call to write a single byte @ position set by lseek.
if (write(fd, " ", 1) == -1)
{
    perror("Write function error.");
    //return 1;
}

close(fd);
return 0;