首页 > 系统相关 >Linux学习之文件操作

Linux学习之文件操作

时间:2024-08-17 17:39:27浏览次数:7  
标签:文件 char Linux argv 学习 stu fd printf include

程序

点击查看代码
/*
    创建命令行参数输入名字的文件
    存储用户输入的学生姓名年龄和成绩
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

struct Student
{
    char name[25];
    int age;
    double score;
} stu = {"司徒寇", 25, 59.99};

int main(int argc, char *argv[]) // 程序的入口点,接受命令行参数。
{
    if (argc < 2)
    {
        printf("请命令行输入文件名!\n");
        exit(-1); // 结束当前进程
    }

    int fd;
    fd = open(argv[1], O_WRONLY); // 写入模式
    if (-1 == fd)                 // 文件不存在
    {
        printf("打开%s失败:%m\n", argv[1]); // %m->失败原因
        printf("尝试创建文件!\n");
        fd = open(argv[1], O_WRONLY | O_CREAT, 0666);
        if (-1 == fd)
        {
            printf("创建%s失败!失败原因:%m\n", argv[1]);
            exit(-1);
        }
        printf("创建文件成功!\n");
    }
    printf("打开文件成功!\n");
    printf("%s - %d - %g\n", stu.name, stu.age, stu.score);

#if 0
	write(fd,(const char*)&stu,sizeof(stu));
#else
    write(fd, stu.name, sizeof(stu.name));
    write(fd, (const char *)&(stu.age), sizeof(stu.age));
    write(fd, (const char *)&(stu.score), sizeof(stu.score));
#endif
    printf("over!\n");
    close(fd);
}

执行

在终端执行以下操作:


第一次执行结果:

第二次执行结果:

标签:文件,char,Linux,argv,学习,stu,fd,printf,include
From: https://www.cnblogs.com/songpoetry/p/18364691

相关文章