> 技术文档 > [系统编程]#2 文件I/O

[系统编程]#2 文件I/O


概念

文件I/O(输入/输出)是指计算机与存储设备之间进行数据传输的过程。它涉及到读取和写入文件,是程序设计中非常基础且重要的一部分。以下是对文件I/O的基本介绍:

文件操作的基本步骤

打开文件

在对文件进行任何操作之前,首先需要通过编程语言提供的相应函数或方法打开文件。打开文件时通常需要指定模式,比如只读、只写、追加等。

读写文件

一旦文件被打开,就可以对其进行读操作或者写操作了。根据不同的需求,可以选择逐字节、逐行或按照特定大小的块来读写数据。

关闭文件

完成所有对文件的操作后,应该及时关闭文件。这一步很重要,因为它可以释放与文件关联的资源,并确保所有未写入的数据都被正确地保存到磁盘上。

常见的文件模式

只读(\"r\")

打开一个已存在的文件用于读取。如果文件不存在,则打开失败。

只写(\"w\")

打开一个文件用于写入。如果文件存在,则其内容会被清空;如果文件不存在,则会创建新文件。

追加(\"a\")

打开一个文件用于追加数据。如果文件存在,则数据会被添加到文件末尾;如果文件不存在,则会创建新文件。

读写(\"r+\" 或 \"w+\" 等)

同时支持读取和写入的模式,具体行为依赖于所使用的标志。

编程中的文件I/O

不同的编程语言提供了各自处理文件I/O的方法。例如,在Python中,可以使用内置的open()函数来打开文件,并通过返回的文件对象调用.read(), .write()等方法进行读写操作;而在C语言中,则需要使用标准库函数如fopen(), fread(), fwrite()等来进行文件操作。

注意事项

在处理文件时,务必注意错误处理,比如文件不存在、权限不足等情况。
为了防止数据丢失或损坏,应该总是确保文件在不再使用时被正确关闭。
考虑到性能问题,对于频繁的小规模读写操作,可能需要使用缓冲技术。
根据实际的应用场景和使用的编程语言,具体的实现细节可能会有所不同。


相关操作函数

1.open

#include #include #include #include #include #include int main(int argc, char **argv){ // fopen(,\"w\") int flag = 234092; int fd = open(\"1.txt\", O_WRONLY | O_CREAT | O_TRUNC, 0666); if (-1 == fd) { printf(\"open error\\n\"); return 1; } // system(\"pause\"); return 0;}

2.write

#include #include #include #include #include #include #include int main(int argc, char **argv){ // open //read /write //close // fopen(,\"w\") int fd = open(\"1.txt\", O_WRONLY | O_CREAT | O_TRUNC, 0666); if (-1 == fd) { printf(\"open error\\n\"); return 1; } char buf[128]=\"hello\"; ssize_t ret = write(fd,buf,strlen(buf)); // 第三个参数 有效数据的长度 // ret>0 实际写入的字节数 ==0 一个字符也没有写入(不是错误,和设备有关) -1 错误 // system(\"pause\"); printf(\"ret :%ld\\n\",ret); close(fd); return 0;}

3.read

#include #include #include #include #include #include #include int main(int argc, char **argv){ int fd = open(\"1.txt\", O_RDONLY); if (-1 == fd) { printf(\"open error\\n\"); return 1; } while (1) { char buf[1024] = {0}; int ret = read( fd, buf, sizeof(buf)); // 第三参数 可以比实际内容大 ,返回值代表实际读到的字节数 // ret >0 实际读到字节数 ==0 end of file -1 错误 if (0 == ret) { break; } printf(\"%s\\n\", buf); } close(fd); // system(\"pause\"); return 0;}

4.结合实现的cp功能

#include #include #include #include #include #include #include int main(int argc, char **argv){ if(argc<3) { printf(\"usage:%s srcfile dstfile\\n\",argv[0]); return 1; } int srcfd = open(argv[1],O_RDONLY); int dstfd = open(argv[2],O_WRONLY|O_CREAT|O_TRUNC,0666); if (-1 == srcfd || -1 == dstfd) { printf(\"open error\\n\"); return 1; } while(1) { char buf[4096]={0}; int ret = read(srcfd,buf,sizeof(buf)); if(0 == ret) { break; } write(dstfd,buf,ret); } close(dstfd); close(srcfd); return 0;}

5.lseek

#include #include #include #include #include #include #include int main(int argc, char **argv){ int fd = open(\"1.txt\",O_RDWR); // r+ if (-1 == fd) { printf(\"open error\\n\"); return 1; } int ret = lseek(fd,10,SEEK_SET); if(-1 == ret) { printf(\"lseek error\\n\"); return 1; } printf(\"offset %d\\n\",ret); write(fd,\"stdio\",5); close(fd); return 0;}

6.fileno

#include #include #include #include #include intmain(int argc, char **argv){ FILE* fp = fopen(\"1.txt\",\"r\"); if(NULL == fp) { return 1; } int fd = fileno(fp); if(-1 == fd) { return 1; } char buf[256]={0}; read(fd,buf,sizeof(buf)-1); printf(\"%s\\n\",buf); fclose(fp); //system(\"pause\"); return 0;}

7.fdopen

#include #include #include #include #include intmain(int argc, char **argv){ int fd = open(\"1.txt\",O_RDONLY); if(-1 == fd) { return 1; } FILE* fp = fdopen(fd,\"r\"); if(NULL == fp) { return 1; } char buf[256]={0}; fgets(buf,sizeof(buf),fp); printf(\"%s\\n\",buf); fclose(fp); //system(\"pause\"); return 0;}

结合实现的ls功能部分:

8.ls

#include #include #include #include #include #include int main(int argc, char **argv){ DIR * dir = opendir(\"./\"); if(NULL == dir) { printf(\"opendir error\\n\"); return 1; } while(1) { struct dirent *info = readdir(dir); if(NULL == info) { break; } switch (info->d_type) { case DT_REG: printf(\"普通文件\\t\"); break; case DT_DIR: printf(\"目录文件\\t\"); break; default: printf(\"其他文件\\t\"); break; } printf(\"%s\\n\",info->d_name); } closedir(dir); //system(\"pause\"); return 0;}

9.getcwd

#include #include intmain(int argc, char **argv){ char curpath[512]={0}; getcwd(curpath,sizeof(curpath)); // pwd(shell) printf(\"cur:%s\\n\",curpath); chdir(\"../\"); fopen(\"3.txt\",\"w\"); getcwd(curpath,sizeof(curpath)); // pwd(shell) printf(\"changed :%s\\n\",curpath); // system(\"pause\"); return 0;}

10.mkdir

#include #include #include int main(int argc, char **argv){ int ret = mkdir(\"123\",0777); //7 111 rwx if(-1 == ret) { printf(\"mkdir error\\n\"); return 1; } //system(\"pause\"); return 0;}

11.rmdir

#include #include #include #include int main(int argc, char **argv){ int ret = rmdir(\"123\"); if (-1 == ret) { printf(\"rmdir\"); return 1; } // system(\"pause\"); return 0;}

12.cnt_proc

#include #include #include #include #include #include int isnum(char * name){ while(*name) { if(*name >=\'0\' && *named_name); if (DT_DIR == info->d_type && isnum(info->d_name)) { num++; } } closedir(dir); printf(\"num:%d\\n\", num); // system(\"pause\"); return 0;}

13.ls_r

#include #include #include #include #include #include int do_ls(char *path){ DIR *dir = opendir(path); if (NULL == dir) { printf(\"opendir error %s\\n\",path); return 1; } while (1) { struct dirent *info = readdir(dir); if (NULL == info) { break; } // printf(\"%s\\n\",info->d_name); char newpath[512] = {0}; sprintf(newpath, \"%s/%s\", path, info->d_name); if (DT_DIR == info->d_type) // /home/linux/ { // . .. if(0 == strcmp(info->d_name,\".\") || 0 == strcmp(info->d_name,\"..\")) { continue; } do_ls(newpath); } else { printf(\"%s\\n\",newpath); } } closedir(dir); return 0;}int main(int argc, char **argv){ //do_ls(\"/home/linux/20250623_cd\"); if(argc<2) { printf(\"usage:%s path_name\\n\",argv[0]); return 1; } do_ls(argv[1]); // system(\"pause\"); return 0;}

14.stat

#include #include #include #include int main(int argc, char **argv){ struct stat st; int ret = stat(\"./01ls.c\",&st); if(-1 == ret) { printf(\"stat error\\n\"); return 1; } printf(\"ino:%lu mode:%d link:%lu uid:%d gid:%d size:%lu tm:%lu\\n\" ,st.st_ino,st.st_mode,st.st_nlink, st.st_uid,st.st_gid,st.st_size,st.st_mtime); // system(\"pause\"); return 0;}

15.ll

#include #include #include #include int main(int argc, char **argv){ struct stat st; char filename[]=\"./01ls.c\"; int ret = stat(filename, &st); if (-1 == ret) { printf(\"stat error\\n\"); return 1; } // -rwxrwxrwx 1 linux linux 493 Jul 4 14:52 01ls.c* // man 7 inode if (S_ISREG(st.st_mode)) { fputc(\'-\', stdout); } else if (S_ISDIR(st.st_mode)) { fputc(\'d\', stdout); } else if (S_ISCHR(st.st_mode)) { fputc(\'c\', stdout); } else if (S_ISBLK(st.st_mode)) { fputc(\'b\', stdout); } else { fputc(\'o\', stdout); // other } // -rwxrwxrwx 1 linux linux 493 Jul 4 14:52 01ls.c* if (st.st_mode & S_IRUSR) { fputc(\'r\', stdout); } else { fputc(\'-\', stdout); } if (st.st_mode & S_IWUSR) { fputc(\'w\', stdout); } else { fputc(\'-\', stdout); } if (st.st_mode & S_IXUSR) { fputc(\'x\', stdout); } else { fputc(\'-\', stdout); } // -rwxrwxrwx 1 linux linux 493 Jul 4 14:52 01ls.c* printf(\" %lu %d %d %lu %lu %s\\n\" ,st.st_nlink,st.st_uid,st.st_gid ,st.st_size,st.st_mtime,filename); // system(\"pause\"); return 0;}

时间部分

16.time

#include #include int main(int argc, char *argv[]){ time_t tm; time(&tm); printf(\"%ld\\n\",tm); return 0;}

17.ctime

#include #include int main(int argc, char *argv[]){ time_t tm; time(&tm); printf(\"%s\\n\",ctime(&tm)); return 0;}

18.localtime

#include #include int main(int argc, char *argv[]){ time_t tm; time(&tm); struct tm * tm_info = localtime(&tm); printf(\"%d-%d-%d %d:%d:%d\\n\",tm_info->tm_year+1900,tm_info->tm_mon+1,tm_info->tm_mday  ,tm_info->tm_hour,tm_info->tm_min,tm_info->tm_sec); return 0;}

19.getpwname

#include #include #include int main(int argc, char *argv[]){ int uid = 1000; struct passwd* pw = getpwuid(uid); if(NULL == pw) { return 1; } printf(\"%s %s %d %s\\n\",pw->pw_name,pw->pw_passwd, pw->pw_gid,pw->pw_dir); return 0;}

20.getgrgid

#include #include #include //  char ** int main(int argc, char *argv[]){ int gid =1000; struct group* gr = getgrgid(gid); printf(\"%s %s \",gr->gr_name,gr->gr_passwd); int i= 0 ; while(NULL != gr->gr_mem[i]) { printf(\"%d %s\\n\",i,gr->gr_mem[i++]); } return 0;}

21.perror

#include int main(int argc, char *argv[]){ FILE* fp = fopen(\"aaa\",\"r\"); if(NULL == fp) { //printf(\"open error\\n\"); perror(\"fopen error\"); return 1; } return 0;}

22.strerror

#include #include int main(int argc, char *argv[]){ int i = 0; for(i= 0 ;i<255;i++) { printf(\"%d %s\\n\",i,strerror(i)); } return 0;}

23.error

#include #include #include  int main(int argc, char *argv[]){ FILE* fp = fopen(\"aaa\",\"r\"); if(NULL == fp) { error(1,errno,\"filename:%s func:%s line:%d\",__FILE__,__func__,__LINE__); printf(\"aaaaaaaaaaa\\n\"); return 1; } return 0;}