Linux下的IO/文件操作练习,知识虽然简单 但是往往基础容易被忽略,偶尔的练习是有必要的。
练习printf
/************************************************************************* > File Name: printf.c > Author: > Mail: > Created Time: Wed 11 Feb 2015 01:08:15 AM PST ************************************************************************/ #include<stdio.h> int main() { printf("%10s\n","hello"); printf("%-10s\n","hello"); printf("%s\n","hello") ; printf("%*s\n",10,"hello") ; printf("%010d\n",100) ; printf("%10.4g\n",1.22) ; printf("%10s\n","Hello,I am a programmer !") ; return 0 ; }
练习C标准库的文件复制 相比系统调用 会快 因为有缓冲
/************************************************************************* > File Name: cpy.c > Author: > Mail: > Created Time: Wed 11 Feb 2015 01:37:56 AM PST ************************************************************************/ #include<stdio.h> int main() { int c; FILE*in=fopen("./printf","r"); FILE*out=fopen("./printf_tem","w"); while((c=fgetc(in))!=EOF) { fputc(c,out) ; } exit(0); }
练习查看一个文件的状态
/************************************************************************* > File Name: fileinfo.c > Author: > Mail: > Created Time: Wed 11 Feb 2015 11:25:21 PM PST ************************************************************************/ #include<stdio.h> #include<sys/stat.h> #include<unistd.h> int main() { int fileNo; struct stat fileStat ; FILE*pFile= fopen("./cpy","r"); if(pFile==NULL) { printf("File Open Error!\n") ; exit(0); } fileNo= fileno(pFile); printf("FileNumber:%d\n",fileNo) ; if(-1==fstat(fileNo,&fileStat)) { printf("GetFileInfo Error!\n") ; exit(0) ; } printf("DeviceID:%d\n",fileStat.st_dev); printf("UserID:%d\n",fileStat.st_uid); printf("GroupID:%d\n",fileStat.st_gid); printf("FileSize:%d\n",fileStat.st_size); return 0 ; }
我们模拟Linux下的ls程序
/************************************************************************* > File Name: listdir.c > Author: > Mail: > Created Time: Thu 12 Feb 2015 12:49:13 AM PST ************************************************************************/ #include<stdio.h> #include<unistd.h> #include<sys/stat.h> #include<dirent.h> #include<string.h> #include<sys/types.h> void list_func(char*path,int depth) { DIR*pDirHandle= opendir(path); struct dirent * dent ; struct stat fstat ; if(pDirHandle==NULL) { printf("OpenDir %s Error!\n",path); exit(0); } chdir(path); while((dent=readdir(pDirHandle))!=NULL) { //error then return -1 lstat(dent->d_name,&fstat); if(S_ISDIR(fstat.st_mode)) { //remove director . and .. if(strcmp(".",dent->d_name)==0|| strcmp("..",dent->d_name)==0 ) continue ; printf("%*s%s/\n",depth,"",dent->d_name) ; list_func(dent->d_name,depth+4) ; }else printf("%*s%s\n",depth,"",dent->d_name); } chdir(".."); closedir(pDirHandle); } int main(int argc,char**argv) { if(argc<2) { printf("Param Format: listdir path\n"); return ; } char*pDirPath=argv[1]; int depath=0; printf("List Begin:\n"); list_func(pDirPath,depath) ; printf("List End.\n"); return 0 ; }
时间: 2024-10-12 03:21:29