c python shell文件读写

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_38637595/article/details/78166658

linux

#include <stdio.h>
//#include <sys/types.h>
//#include <sys/stat.h>
#include <fcntl.h>      //headfile of open
#include <errno.h>      //headfile of errno
#include <string.h>     //headfile of sterror
#include <unistd.h>     //headfile of read

void readFile(){
        char filepath[] = "/home/zijing/readfile.txt";
        int     fd = open(filepath, O_RDONLY);
        if(fd == -1){
                printf("read error, %s -->  %s\n",filepath, strerror(errno));

                return;
        }
//      printf("success fd = %d\n", fd);
        char buf[100];
        memset(buf,0,sizeof(buf));

        while(read(fd, buf, sizeof(buf) - 1) > 0){
                printf("%s\n", buf);
                memset(buf, 0, sizeof(buf));
        }
        printf("%s\n",buf);
        close(fd);
}

void writeFile(){
        char filepath[] = "/home/zijing/writefile.txt";
        int     fd = open(filepath, O_RDWR | O_APPEND);

        if (fd == -1){
                printf("write error, %s -- > %s\n", filepath, strerror(errno));
                return;
        }

//      printf("success fd = %d\n", fd);
        char buf[100];
        memset(buf, 0, sizeof(buf));
        strcpy(buf, "hello linux from c\n");
        write(fd,buf,strlen(buf));
        close(fd);
}

int main(int arg, char *args[]) {
        readFile();
        writeFile();
        return 0;
}

python

def readfileOnce():
        file = open('/home/zijing/readfile.txt', encoding='utf-8')
        data = file.read()
        file.close()
        print(data,end='')                      #end line without '\n'


def readfileBylist():
        file = open('/home/zijing/readfile.txt','r',encoding='utf-8')
        for line in file.readlines():
                print(line,end = '')    #end line without '\n'
        file.close()

def readfileBylines():
        # high efficent
        file = open('/home/zijing/readfile.txt','r',encoding='utf-8')
        for line in file:
                print(line,end = '')    #end line without '\n'
        file.close()


def writefile():
        file = open('/home/zijing/writefile.txt','a',encoding='utf-8')
        file.write("hello linux from python\n")
        file.close()


readfileOnce()
readfileBylist()
readfileBylines()
writefile()

shell

#!/bin/bash
#sign:          2017/9/17       zijing
#funtion:       file opreate of read and file


FILEPATH="/home/zijing/readfile.txt"
FILEWRITEPATH="/home/zijing/writefile.txt"

function readfile(){
        cat $FILEPATH | while read line; do
        echo $line;
        done
}

function writefile(){
        echo "hello linux from shell" >> $FILEWRITEPATH
}

readfile
writefile

猜你喜欢

转载自blog.csdn.net/weixin_38637595/article/details/78166658
今日推荐