1.打开关闭流
#include<stdio.h>
定义函数 FILE * fopen(const char * path,const char * mode);
函数说明 参数path字符串包含欲打开的文件路径及文件名,参数mode字符串则代表着流形态。
mode有下列几种形态字符串:
r 打开只读文件,该文件必须存在。
r+ 打开可读写的文件,该文件必须存在。
w 打开只写文件,若文件存在则文件长度清为0,即该文件内容会消失。若文件不存在则建立该文件。
w+ 打开可读写文件,若文件存在则文件长度清为零,即该文件内容会消失。若文件不存在则建立该文件。
a 以附加的方式打开只写文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾,即文件原先的内容会被保留。
a+ 以附加方式打开可读写的文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾后,即文件原先的内容会被保留。
上述的形态字符串都可以再加一个b字符,如rb、w+b或ab+等组合,加入b 字符用来告诉函数库打开的文件为二进制文件,而非纯
文字文件。不过在POSIX系统,包含Linux都会忽略该字符。由fopen()所建立的新文件会具有
S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH(0666)权限,此文件权限也会参考umask值。
返回值 文件顺利打开后,指向该流的文件指针就会被返回。若果文件打开失败则返回NULL,并把错误代码存在errno 中。
附加说明 一般而言,开文件后会作一些文件读取或写入的动作,若开文件失败,接下来的读写动作也无法顺利进行,所以在fopen()后请作错误判断及处理。
#include<stdio.h>
定义函数 FILE * fdopen(int fildes,const char * mode);
函数说明 fdopen()会将参数fildes 的文件描述词,转换为对应的文件指针后返回。参数mode 字符串则代表着文件指针的流形态,此形态必须和原先文件描述词读写模式相同。关于mode 字符串格式请参考fopen()。
返回值 转换成功时返回指向该流的文件指针。失败则返回NULL,并把错误代码存在errno中。
fdopen用于在一个已经打开的文件描述符上打开一个流。
关闭流:
#include<stdio.h>
定义函数 int fclose(FILE * stream);
函数说明 fclose()用来关闭先前fopen()打开的文件。此动作会让缓冲区内的数据写入文件中,并释放系统所提供的文件资源。
返回值 若关文件动作成功则返回0,有错误发生时则返回EOF并把错误代码存到errno。
错误代码 EBADF表示参数stream非已打开的文件。
在fclose关闭文件时,该函数会将保存在内存中尚未来得及写回磁盘的文件内容写到磁盘上。
2.以字符为单位读写数据
include<stdio.h>
定义函数 nt fgetc(FILE * stream);
函数说明 fgetc()从参数stream所指的文件中读取一个字符。若读到文件尾而无数据时便返回EOF。
返回值 getc()会返回读取到的字符,若返回EOF则表示到了文件尾。
#include<stdio.h>
定义函数 int fputc(int c,FILE * stream);
函数说明 fputc 会将参数c 转为unsigned char 后写入参数stream 指定的文件中。
返回值 fputc()会返回写入成功的字符,即参数c。若返回EOF则代表写入失败。
范例:
//copy.c
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[ ])
{
FILE *fp1, *fp2;
int c;
if(argc != 3){
printf("wrong command/n");
exit(1);
}
if((fp1 = fopen(argv[1], "rb")) == NULL){
perror("fail to open");
exit(1);
}
if((fp1 = fopen(argv[2], "wb")) == NULL){
perror("fail to open");
exit(1);
}
while((c = fgetc(fp1)) != EOF){
if(fputc(c, fp2) == EOF){
perror("fail to write");
exit(1);
}
if(fputc(c, STDOUT_FILENO) == EOF){
perror("fail to write");
exit(1);
}
}
if(errno != 0){
perror("fail to read");
exit(1);
}
fclose(fp1);
fclose(fp2);
return 0;
}
3.以行为单位读写数据
include<stdio.h>
定义函数 char * fgets(char * s,int size,FILE * stream);
函数说明 fgets()用来从参数stream所指的文件内读入字符并存到参数s所指的内存空间,直到出现换行字符、读到文件尾或是已读了size-1个字符为止,最后会加上NULL('/0')作为字符串结束。
返回值 gets()若成功则返回s指针,返回NULL则表示有错误发生。
该函数也会将'/n'读入缓冲区,因此缓冲区中实际有效的内容应该是缓冲区实际字节数(不包括'/0')减1 .
#include<stdio.h>
定义函数 char * gets(char *s);
函数说明 gets()用来从标准设备读入字符并存到参数s所指的内存空间,直到出现换行字符或读到文件尾为止,最后加上NULL作为字符串结束。
返回值 gets()若成功则返回s指针,返回NULL则表示有错误发生。
附加说明 由于gets()无法知道字符串s的大小,必须遇到换行字符或文件尾才会结束输入,因此容易造成缓冲溢出的安全性问题。建议使用fgets()取代。
该函数从标准输入读入一行,但是并不读入'/n'
#include<stdio.h>
定义函数 int fputs(const char * s,FILE * stream);
函数说明 fputs()用来将参数s所指的字符串写入到参数stream所指的文件内。
返回值 若成功则返回写出的字符个数,返回EOF则表示有错误发生。
#include<stdio.h>
定义函数 int puts(const char * s);
该函数用于向标准输出输出字符串,而且会自动输出'/n'
4.逐行读取文件的内容
使用fgets函数即可。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 1024
int main()
{
char buf[MAX];
FILE * fp;
int len;
if((fp=fopen("test.txt"."r"))==NULL){
perror("fail to open");
exit(1);
}
while(fgets(buf,MAX,fp)!=NULL){
len=strlen(buf);
buf[len-1]='/0';//去掉换行符
printf("%s %d/n",buf,len-1);
}
return 0;
}
5.输出xml形式的配置文件
将如下格式的.ini配置文件转化为.xml文件
#config of network 有关网络的配置信息
!network
ip=192.168.11.6
port=8000
home-path=/home/admin/
转化为:
<!-- config of network -->
<network>
<ip>192.168.11.6</ip>
<port>8000</port>
<home-path>/home/admin/</home-path>
</network>
程序:
//convert.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#define FILE_LEN 64
#define MAX_LINE 128
#define LINE 8
int main(int argc, char *argv[])
{
FILE *in, *out;
char file_name[FILE_LEN];
char buf[MAX_LINE];
char outbuf[MAX_LINE];
char head[LINE];
char *p;
int len;
if(argc != 2){
printf("wrong usage/n");
exit(1);
}
len = strlen(argv[1]);
if(strcmp(&argv[len - 3], "ini") != 0){ //扩展名需要为.ini
printf("source file error/n");
exit(1);
}
in = fopen(argv[1], "rb");
if(in == NULL){
perror("fail to open");
exit(1);
}
strcpy(file_name, argv[1]);
strcpy(&file_name[len - 3], "xml");//生成xml文件的名字
out = fopen(file_name, "wb");
if(out == NULL){
perror("fail to open");
exit(1);
}
while(fgets(buf, MAX_LINE, in) != NULL){ //顺序读取一行
len = strlen(buf);
buf[len - 1] = '/0';//去掉换行符
if(buf[0] == '#') //如果是书写配置信息头
sprintf(outbuf, "<!-- %s -->/n", buf);
else if(buf[0] == '!'){
sprintf(outbuf, "<%s>/n", buf);
strcpy(head, buf); //复制一份,用于后面输出</head>
}else if(buf[0] = '/0')//遇到空行,说明一个配置信息结束,输出及配置信息结尾
sprintf(outbuf, "</%s>/n/n", head);
else{
p = strtok(buf, "=");//将原配置信息的一行拆分为配置选项和配置内容
sprintf(outbuf, "/t<%s>%s</%s>/n", buf, p, buf);
}
if(fputs(outbuf, out) == NULL){ //将准备好的输出信息输出,每行输出一次
perror("fail to write");
exit(1);
}
}
if(errno != 0){
perror("fail to read");
exit(1);
}
fclose(in);
fclose(out);
return 0;
}
6.读写数据块
基于流,直接读取数据块
#include<stdio.h>
定义函数 size_t fread(void * ptr,size_t size,size_t nmemb,FILE * stream);
函数说明 fread()用来从文件流中读取数据。参数stream为已打开的文件指针,参数ptr 指向欲存放读取进来的数据空间,读取的字符数以参数size*nmemb来决定。Fread()会返回实际读取到的nmemb数目,如果此值比参数nmemb 来得小,则代表可能读到了文件尾或有错误发生,这时必须用feof()或ferror()来决定发生什么情况。
返回值 返回实际读取到的nmemb数目。
范例:
#include<stdio.h>
#define nmemb 3
struct test
{
char name[20];
int size;
}s[nmemb];
main()
{
FILE * stream;
int i;
stream = fopen(“/tmp/fwrite”,”r”);
fread(s,sizeof(struct test),nmemb,stream);
fclose(stream);
for(i=0;i<nmemb;i++)
printf(“name[%d]=%-20s:size[%d]=%d/n”,i,s[i].name,i,s
[i].size);
}
#include<stdio.h>
定义函数 size_t fwrite(const void * ptr,size_t size,size_tnmemb,FILE * stream);
函数说明 fwrite()用来将数据写入文件流中。参数stream为已打开的文件指针,参数ptr 指向欲写入的数据地址,总共写入的字符数以参数size*nmemb来决定。Fwrite()会返回实际写入的nmemb数目。
返回值 返回实际写入的nmemb数目。
范例:
#include<stdio.h>
#define set_s (x,y) {strcoy(s[x].name,y);s[x].size=strlen
(y);}
#define nmemb 3
struct test
{
char name[20];
int size;
}s[nmemb];
main()
{
FILE * stream;
set_s(0,”Linux!”);
set_s(1,”FreeBSD!”);
set_s(2,”Windows2000.”);
stream=fopen(“/tmp/fwrite”,”w”);
fwrite(s,sizeof(struct test),nmemb,stream);
fclose(stream);
}
7.实现自己的cp命令
//copy.c
#include <stdio.h>
#include <stdlib.h>
/* 程序使用方法:copy src des
* 本程序并未做输入的出错处理,例如文件路径的正确性以及目标文件已经是否存在等
*/
int main(int argc, char *argv[ ])
{
FILE *fp1, *fp2; /* 源文件和目标文件 */
char buf[1024];
int n;
if(argc != 3){ /* 检查参数个数 */
printf("wrong command/n");
exit(1);
}
if((fp1 = fopen(argv[1], "rb")) == NULL){ /* 打开源文件 */
perror("fail to open");
exit(1);
}
if((fp2 = fopen(argv[2], "wb")) == NULL){ /* 打开目标文件 */
perror("fail to open");
exit(1);
}
/* 开始复制文件,文件可能很大,缓冲一次装不下,所以使用一个循环进行读写 */
while((n = fread(buf, sizeof(char), 1024, fp1)) > 0){ /* 读源文件,直到将文件内容全部读完 */
if(fwrite(buf, sizeof(char), n, fp2) == -1){ /* 将读出的内容全部写到目标文件中去 */
perror("fail to write");
exit(1);
}
}
if(n == -1){ /* 如果应为读入字节小于0而跳出循环则说明出错了 */
perror("fail to read");
exit(1);
}
fclose(fp1); /* 关闭源文件和目标文件 */
fclose(fp2);
return 0;
}
8.字符统计
统计某文件中字母数,数字数,和空格数。
//sum.c
#include <stdio.h>
#include <stdlib.h>
#define MAX 1024
int main(void)
{
FILE *fp;
char buf[MAX];
int n;
char *p;
int letter, number, blank;
fp = fopen("text.txt", "rb"); /* 打开该文件 */
if(fp == NULL){
perror("fail to open");
exit(1);
}
letter = 0;
number = 0;
blank = 0;
/* 循环读取文件的内容,该文件可能很大,不能一次读入到缓冲区中 */
while((n = fread(buf, sizeof(char), MAX - 1, fp)) > 0){
buf[n] = '/0'; /* 手动设置结束符 */
p = buf;
while(*p != '/0'){ /* 处理每次读入的文件内容 */
if(('a' <= *p && *p <= 'z') || ('A' <= *p && *p <= 'Z')) /* 判断为字母 */
letter++;
if(*p == ' ') /* 判断为空格 */
blank++;
if('0' <= *p && *p <= '9') /* 判断为数字 */
number++;
p++;
}
}
if(n == -1){ /* 读操作出错 */
perror("fail to read");
exit(1);
}
/* 输出结果,字母数、数字数和空格数 */
printf("the sum of letter is : %d, the sum of number is : %d,
the sum of blank is : %d", letter, number, blank);
return 0;
}
9.目录下所有文件的字符统计
统计某目录下所有文件的字符统计。
//mul_sum.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#define MAX_LINE 128
#define FILE_SIZE 1024
int main(void)
{
FILE *in, out;
FILE *fp;
struct stat statbuf;
char file_name[MAX_LINE];
char *buf;
int n;
char *p;
int file_size = 0;
int letter, number, blank;
if(system("ls > temp.txt") == -1){ //得到当前目录下的目录列表
perror("fail to exec command");
exit(1);
}
fp = fopen("temp.txt", "rb");
if(fp == NULL){
perror("fail to open");
exit(1);
}
out = fopen("res.txt", "wb");
if(out == NULL){
perror("fail to open");
exit(1);
}
while(fgets(file_name, MAX_LINE, fp) != NULL){ //读取一个文件名
if(stat(file_name, &statbuf) == -1){ //得到文件状态
perror("fail to get stat");
exit(1);
}
if(!S_ISDIR(statbuf.st_mode)){ //如果文件是一个目录,跳过
continue;
/*最大分配FILE_SIZE个字节的缓冲区,如果文件太大,则分批读入,如果文件大小小于等于FILE_SIZE,则一次性读入*/
if((file_size = statbuf.st_size) > FILE_SIZE)
file_size = FILE_SIZE;
file_size++; //多出一个位置来设置'/0'
buf = (char *)malloc(sizeof(char) *file_size);
in = fopen(file_name, "rb");
if(in == NULL){
perror("fail to open");
exit(1);
}
letter = 0;
number = 0;
blank = 0;
while((n = fread(buf, sizeof(char), file_size - 1, in)) > 0){
buf[n] = '/0';//手动设置结束符
p = buf;
while(*p != '/0'){
if(('a' <= *p && *p <= 'z') || ('A' <= *p && *p <= 'Z'))
letter++;
if(*p == ' ')
blank++;
if('0' <= *p && *p <= '9')
number++;
p++;
}
}
if(n == -1){
perror("fail to read");
exit(1);
}
/* 输出结果,字母数、数字数和空格数 */
fprintf("%s, he sum of letter is : %d, the sum of number is : %d,
the sum of blank is : %d", file_name, letter, number, blank);
fclose(in);
free(buf); /* 需要释放缓冲区,下一次会分配新的缓冲区 */
}
fclose(fp);
fclose(out);
if(unlink("temp.txt") == -1){ /* 删除保存临时文件的temp.txt文件 */
perror("fail to unlink");
exit(1);
}
return 0;
}