Помимо того, что buf_size
не определено, вы должны ограничить размер «чанка» до buf_size
.
Вот отрефакторинговая версия вашего кода, которая устраняет проблему [вместе с некоторыми другими ошибками] :
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <error.h>
#define buf_size 100
int
main(int argc, char *argv[])
{
//int i = 0;
int fd;
int bytes;
char *file;
char buf[buf_size] = { ' ' };
ssize_t wlen = 0;
if (argc != 3)
error(1, errno, "Too many or less number of arguments\n");
file = argv[1];
// NOTE/BUG: with O_CREAT, you have to supply the mode
// NOTE/BUG: you should probably add O_TRUNC because if you run the
// program twice, once with length of (e.g.) 5000 and then 300, the
// file is _not_ shortened the second time
#if 0
fd = open(file, O_WRONLY | O_CREAT);
#else
fd = open(file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
#endif
printf("The value of the file descriptor is : %d\n", fd);
if (fd == -1)
error(1, errno, "Error in opening the file\n");
printf("Successfully opened the file\n");
bytes = atoi(argv[2]);
#if 0
while (1) {
wlen = write(fd, buf, bytes);
if (wlen == -1)
error(1, errno, "Error in writing the file\n");
bytes = bytes - wlen;
if (bytes == 0)
return 0;
}
#else
for (; bytes > 0; bytes -= wlen) {
wlen = bytes;
if (wlen > buf_size)
wlen = buf_size;
wlen = write(fd, buf, wlen);
if (wlen == -1)
error(1, errno, "Error in writing the file\n");
}
#endif
if (close(fd) == -1)
error(1, errno, "Error in closing the file\n");
return 0;
}