底层文件操作函数:
#include<unistd.h> int open(const char* pathname,int flags); int open(const char* pathname,int flags,mode_t mode);
//返回值:成功,返回文件描述符 失败,返回-1,失败原因记录在errno中
int close(int fd); //返回值:成功返回0 失败返回-1
size_t read(int fd,void *buffer,sizeof(buffer)); size_t write(int fd,void *buffer,sizeof(buffer));
int ioctl(int fd,int request);
例子:
//write.c #include<stdio.h> #include<unistd.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> int main() { int fd,size; char s[]="this is a linux program!\n",buffer[50]; fd=open("temp.txt",O_WRONLY|O_CREAT|O_EXCL); write(fd,s,sizeof(s)); close(fd); fd=open("temp.txt",O_RDONLY); read(fd,buffer,sizeof(buffer)); close(fd); printf("%s\n",buffer); return 0; }
标准文件操作函数:
#include<stdio.h> FILE *fopen(const char* path,const char* mode); //失败返回NULL int fclose(FILE *stream); //成功返回0,失败返回EOF
#include<stdio.h> size_t fread(void *ptr,size_t size,size_t nmemb,FILE *stream); size_t fwrite(const void *ptr,size_t size,size_t nmemb,FILE *stream);
例子:
#include <stdio.h> int main(int argc, char **argv) { FILE *ptr; int i,numread,numwritten,length; length=20; char data[length]; if((ptr=fopen("temp.txt","w+"))!=NULL){ for(i=0;i<length;++i) data[i]='a'+i; numwritten = fwrite(data,sizeof(char),length,ptr); printf("wrote %d words!\n",numwritten); fclose(ptr); } else printf("open files failed!\n"); if((ptr=fopen("temp.txt","r+"))!=NULL){ numread=fread(data,sizeof(char),length,ptr); printf("%s\n",data); printf("read %d words!\n",numread); fclose(ptr); } else printf("open files failed!\n"); return 0; }
读写文件文字符函数:
#include<stdio.h> int getc(FILE *stream); int fputc(int c,FILE *stream); char* fgets(char *s,int size,FILE *stream); char* fputs(const char *s,FILE *stream);
例子:
//fputc.c #include <stdio.h> int main(int argc, char **argv) { int fd,size; char c; FILE* stream=fopen("temp.txt","a+"); c=fgetc(stream); printf("%c\n",c); c=fputc(c,stream); printf("%c\n",c); return 0; }
文件移动和重命名:
#include<stdio.h> int remove(const char* pathname); int rename(const char* oldpath,const char* newpath); //检查读写是否有误 int access(const char* pathname,int mode);
例子:
//remove.c #include <stdio.h> int main(int argc, char **argv) { int flag; char s[]="temp.txt"; flag=remove(s); if(flag==0) printf("delte the file!\n"); else printf("failed!\n") return 0; }
//rename.c #include <stdio.h> int main(int argc, char **argv) { int flag; char old[]="temp.txt"; char new[]="/root/yy/new.txt"; flag=rename(old,new); if(flag==0) printf("rename succeed!\n"); else printf("failed!\n") return 0; }
本文 由 cococo点点 创作,采用 知识共享 署名-非商业性使用-相同方式共享 3.0 * 许可协议进行许可。欢迎转载,请注明出处:
转载自:cococo点点 http://www.cnblogs.com/coder2012