使用fgets统计文件个数
#include <stdio.h>
#include <string.h>
int main(int argc, const char *argv[])
{
FILE *fp = fopen(argv[1],"r");
if(NULL == fp)
{
perror("fopen");
return -1;
}
char buf[20] ="";
int count = 0;
while(fgets(buf,20,fp)!=NULL)
{
count+=strlen(buf);
bzero(buf,sizeof(buf));
}
printf("该文件一共有%d个byte\n",count);
return 0;
}
使用fgets计算一个文件有多少行
#include <stdio.h>
#include <string.h>
int main(int argc, const char *argv[])
{
FILE *fp = fopen(argv[1],"r");
if(NULL == fp)
{
perror("fopen");
return -1;
}
char buf[20] ="";
int count = 0,len = 0;
while(fgets(buf,20,fp)!=NULL)
{
len=strlen(buf);
if('\n' == buf[len-1])
{
count++;
}
bzero(buf,sizeof(buf));
}
printf("该文件一共有%d个\\n\n",count);
return 0;
}
使用文档记录时间
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, const char *argv[])
{
time_t t;
struct tm *tp;
FILE * fp = fopen("./time.txt","a+");
if(NULL == fp)
{
perror("fopen");
return -1;
}
int line=1;
char c;
while((c = fgetc(fp))!=-1)
{
if('\n' == c)
line++;
}
while(1)
{
// system("clear");
time(&t);
tp = localtime(&t);
fprintf(fp,"[%d] %4d-%02d-%02d %02d:%02d:%02d\n",\
line++,tp->tm_year+1900,tp->tm_mon+1,tp->tm_mday,\
tp->tm_hour,tp->tm_min,tp->tm_sec);
fflush(fp);
sleep(1);
}
return 0;
}
文件IO中open函数的flag选项与标准IO中fopen的打开文件方式对应
w: O_WRONLY | O_CREAT | O_TRUNC
r: O_RDONLY
a: O_WRONLY | O_CREAT | O_APPEND
w+: O_RDWR | O_CREAT | O_TRUNC
r+: O_RDWR
a+: O_RDWR | O_CREAT | O_APPEND
O_RDONLY:只读
O_WRONLY:只写
O_WRONLY:可读可写
O_CREAT:如果文件不存在就创建一个文件
O_TRUNC:清空文件内容
O_APPEND:当写的时候文件偏移量移到文件末尾,读还是从文件开始读