#includeC++文件操作int main(int argc,char* argv[]){ char s[40]; //scanf("%s",&s);//可以从文件读也可以从终端读 //printf("%sn",s);//可以写到文件,也可以写到终端 FILE* pfile = fopen(argv[1],"r"); if(NULL==pfile){ printf("open file %s errorn",argv[1]); return 1; } //fscanf(pfile,"%s",&s);//把pfile这个文件指针类型里的argv[1]这个文件内容输入到s里 //fprintf(stdout,"%sn",&s);//输出到终端 fgets(s,sizeof(s),pfile);//可以把全部文件的所有内容(不受空格限制)输入到s里,按s的大小 fclose(pfile); pfile=NULL; printf("%sn",s); FILE* pfile2 = fopen(argv[1],"w");//以可写打开fopen if(NULL==pfile2){ printf("open file %s errorn",argv[1]); return 1; } scanf("%s",&s); fprintf(pfile2,"%sn",s);//把s中的数据把输出到pfile2指向的文件中中 fclose(pfile2); pfile2 = NULL; }
#include#include #include using namespace std; int main(){ string s; cin >> s; ofstream ofs("./test",ios::app); if(ofs){ ofs << s; ofs.close(); } ifstream ifs("./test"); string t; if(ifs){ ifs >> t; ifs.close(); } cout << t << endl; }
//cout/cin printf()/scanf() //ostringstream/istringstream sprintf()/sscanf() //ofstream/ifstream fprintf()/fscanf()管道 匿名管道 单工管道
#include#include using namespace std; int main(){ FILE* pf = popen("./output","r"); if(NULL != pf){ char buff[30] = {" "}; fread(buff,1,sizeof(buff),pf); cout << "read: " << buff << endl; pclose(pf); pf = NULL; } }
#include半双工管道#include using namespace std; int main(){ FILE* pf = popen("./output","w"); if(NULL != pf){ char buff[] = "abjckjnada12345666"; fwrite(buff,1,sizeof(buff),pf); pclose(pf); pf = NULL; } }
一边发 一边收
#includeusing namespace std; #include #include #include int main(){ int fd[2]; pipe(fd); cout << getpid() << endl; if(0 == fork()){ cout << getpid() << ":"; string s; cin >> s; write(fd[1],s.c_str(),s.size()+1); }else{ fcntl(fd[0],F_SETFL,O_NONBLOCK); char buff[30] = {' '}; while(-1 == read(fd[0],buff,sizeof(buff))){ sleep(1); cout << "wait..." << endl; } cout << getpid() << ":" << buff << endl; } close(fd[0]); close(fd[1]); }
两边都可以收发 (非同时)
#include命名管道using namespace std; #include #include #include int main(){ int fd1[2]; int fd2[2]; pipe(fd1); pipe(fd2); cout << getpid() << endl; if(0 == fork()){ for(;;){ cout << getpid() << ":"; string s; cin >> s; write(fd1[1],s.c_str(),s.size()+1); char buff[30] = {' '}; read(fd2[0],buff,sizeof(buff)); cout << getpid() << ":" << buff << endl; } }else{ for(;;){ //fcntl(fd[0],F_SETFL,O_NONBLOCK); char buff[30] = {' '}; while(-1 == read(fd1[0],buff,sizeof(buff))){ sleep(1); cout << "wait..." << endl; } cout << getpid() << ":" << buff << endl; cout << getpid() << ":"; string s; cin >> s; write(fd2[1],s.c_str(),s.size()+1); } }



