Linux编程入门之文件读取和写入

Hello World程序

要求

在Linux环境下编写Hello World程序。要求给出源代码、编译命令、运行结果。

  • 源代码helloworld.cpp
#include
#include

int main(int argc, char *argv[])
{
	printf("Hello NetWork Programming!\n");
    return 0;
}

  • 编译命令
g++ helloworld.cpp -o helloworld

Linux编程入门之文件读取和写入_第1张图片

FileFunction程序

要求

在Linux下编译实现文件的创建、读取、写入、关闭。要求给出源代码、编译命令、运行结果。

  • 源代码fileFunction.cpp
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

// 创建文件
void creatFile(char *fname){
    //判断文件是否已经存在,存在则返回0,否则返回-1
    int st = access(fname, F_OK);   
    if(st == 0){
        printf("The same name of file is exist!!!\n");
        return;
    }
    int fd = creat(fname, S_IRWXU);
    printf("Creat \"%s\" Successfully!!\n", fname);
    close(fd);
    return;
}

// 读取文件内容
void readFile(char *fname){
    int st = access(fname, F_OK);
    
    if(-1 == st){
        printf("The name of \"%s\" isn't exist!!!\n", fname);
        return;
    }

    //获取读取文件的信息
    struct stat statbuf;
    stat(fname, &statbuf);
    if(statbuf.st_size == 0){
        printf("This file is empty!\n");
        return;
    }
    int fd = open(fname, O_RDONLY);
    char buf[statbuf.st_size];
    read(fd, buf, statbuf.st_size);
    printf("%s\n", buf);
    close(fd);
    return;
}

// 向文件写入内容,默认从文件起始位置开始覆盖重写
void writeFile(char *fname, char *iptbuf, int iptsize){
    int fd = open(fname, O_RDWR, S_IRWXU);
    if(fd == -1){
        printf("The file fail to open!!!\n");
    }
    ssize_t size = -1;
    size = write(fd, iptbuf, iptsize);
    printf("write %ld bytes to file \"%s\"\n",size, fname);
    close(fd);
    return;
}

int main(int argc, char *argv[])
{
    //参数判断
    if(argc != 3){
        printf("usage: ./fileFunction [-a] [filename]\n");
        return 0;
    }

    //创建文件
    if(!strcmp("-c", argv[1])){
        creatFile(argv[2]);
        return 0;
    }

    //读取文件
    if(!strcmp("-r", argv[1])){
        readFile(argv[2]);
        return 0;
    }

    //写入内容
    if(!strcmp("-w", argv[1])){
        printf("Please input the size of content: ");
        int iptsize;
        scanf("%d", &iptsize);
        getchar();
        char inputbuf[iptsize] = {0};
        char *ch;
        printf("Please input the content: ");
        // 防止溢出
        std::cin.get(inputbuf, iptsize);
        writeFile(argv[2], inputbuf, strlen(inputbuf));
    }
    return 0;
}
  • 编译命令
g++ fileFunction.cpp -o fileFunction

Linux编程入门之文件读取和写入_第2张图片

你可能感兴趣的:(Linux网络编程,linux,运维,服务器)