2

I have recently started programming in UNIX environment. I need to write a program which creates an empty file with name and size given in the terminal using this commands

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

Here result.txt means the name of the newly created file, and 1000 means the size of the file in bytes.

I know for sure that lseek function moves the file offset, but the trouble is that whenever I run the program it creates a file with a given name, however the size of the file is 0.

Here is the code of my small program.

#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;
}
  • You might like to look at the ftruncate system call. – meuh Feb 26 '16 at 17:21
  • 1
    Your requirements are self contradicting. You first tell you need to write an empty file, which your program does, then that its size need to be of a given value, which implies it has at least some content. A sparse file cannot be but just a big hole. At least its last block need to exist. – jlliagre Feb 26 '16 at 17:23
3

If you're seeking after the end of the file, you have to write at least one byte at that position:

write(fd, "", 1);

to have the OS fill the hole with zeros.

So if you want to create an empty file of a certain size 1000 with lseek, do:

lseek(fd, 999, SEEK_SET); //<- err check
write(fd, "", 1); //<- err check

ftruncate is probably better and it seems to create sparse files without any fuss too:

ftruncate(fd, 1000); 
0

You are not writing anything to the file.

You open the file, move the file descriptor and then you close it.

From the lseek man page

The lseek() function repositions the offset of the file descriptor fildes to the argument offset, according to the directive whence.

0

From the man page --

  The lseek() function allows the file offset to be set beyond the end of the file (but this does not change the size of the file).   If
data  is  later written at this point, subsequent reads of the data in the gap (a "hole") return null bytes ('\0') until data is actually written into the gap.

Use the truncate/ftruncate call to set the file size.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.