linux下可以帮你把头文件和main函数写好的mytouch

来写个丑丑的c和c++混合的 mytouch

有的时候我们想要执行touch自动帮我们生成一个c文件包含我们想要的头文件,但是我们会发现linux下touch出的文件都是空的。当时看到苹果系统下打开一个空的c文件就会给你自动写好 如下形式的c初始程序。

#include<stdio.h>
int main(int argc,char**argv)
{
    
    
	return 0;
}

那我们可不可以在linux下也搞一搞这样的玩样呢?答案是可以的
我们只需要学会一点点文件的操作。
不仅仅可以配置c,甚至还可以配置你想要的任何cpp,java初始化文件

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include<sys/mman.h>
#include<pthread.h>
#include<semaphore.h>
#include <netinet/in.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<sys/select.h>
#include<sys/epoll.h>
#include<dirent.h>
#include<pwd.h>
#include<grp.h>
#include<time.h>
#include<errno.h>
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
#define CONFIGTXT "/home/adl/桌面/linux/小组任务/mytouch.txt"
/*
这里填你需要初始化文件的.txt文件名(其实.c也可),注意要绝对路径。
把你需要的头文件啊,main函数啊都写到.txt中,之后需要从中读取
*/

//我这不伦不类的用了string和char[]不美观!
void mytouch(char*writeFileName,string&configFileName)
{
    
    
    string line;
    struct stat statbuf;
    if(lstat(writeFileName,&statbuf)==-1){
    
    //判断我们需要创建文件是否存在,存在我们就先别覆盖,
    //我觉得覆盖太危险,就直接忽略,当然你可以去自个处理覆盖与否(这里用下c)
            ifstream is(configFileName);
            if(!is){
    
    cerr<<"出错了-----没有配置"<<endl;is.close();exit(1);}
            /*判断配置文件是否存在(这里用了点c++)*/
            ofstream os(writeFileName,ofstream::out|ofstream::trunc);
			/*从配置中一行一行读,再一行一行写入新文件中*/
            while(getline(is,line)){
    
    
                os<<line<<endl;
            }
            os.close();
        }else{
    
    
            puts("文件已经存在,先不操作"); 
            exit(1);
        }
}

int main(int argc,char**argv)
{
    
    
    string configtxt(CONFIGTXT);//默认配置
    if(argc==1){
    
    
        puts("参数少!");
        exit(1);
    }else if(argc==2){
    
    
        mytouch(argv[1],configtxt);//如果有俩参数则第二个参数就是你想创建的c文件
    }else if(argc==3){
    
    
        configtxt=argv[2];
        mytouch(argv[1],configtxt);//如果有仨参数则第三个参数是配置文件(可以是别的类型的文件)
    }
    return 0;   
}

啊啊啊,就是这样,将本目录放入 /etc/environment ,再source一下 /etc/environment
最后

$ mytouch success.c

我的成果!!!

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include<sys/mman.h>
#include<pthread.h>
#include<semaphore.h>
#include <netinet/in.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<sys/select.h>
#include<sys/epoll.h>
#include<dirent.h>
#include<pwd.h>
#include<grp.h>
#include<time.h>
#include<errno.h>
#include<signal.h>
#include<fcntl.h>

int main(int argc,char**argv)
{
    
    
    return 0;
}

yeah~做自己想做的才有意思!

猜你喜欢

转载自blog.csdn.net/adlatereturn/article/details/105303327