C语言练习

C语言练习

2023-06-09
c语言
  • 练习程序。

  • 可以往文件中追加任意大小的数据,适用于创建一个指定大小的文件。
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

/*
 * 以追加的方式向文件中写入数据
 */
int main(int argc, char *argv[])
{
    if (argc != 3) {
        printf("ERROR: Usage: %s filename block_count\n", argv[0]);
        return -1;
    }
    /* 文件的权限还受到Linux的umask影响 */
    int fd = open(argv[1], O_CREAT | O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
    if (fd == -1) {
        printf("ERROR: open error\n");
        return -1;
    }
    
    long count = atol(argv[2]);
    char *buf = (char *)malloc(count);
    for (long i = 0; i < count; i++) {
        buf[i] = 0x33;
    }
    
    /* write buffer to file */
    lseek(fd, 0, SEEK_END);
    return write(fd, buf, count); 
    close(fd);

    free(buf);
    return 0;
}