思维导图
求行数 使用fgets()
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, const char *argv[])
{
FILE *fp = NULL;
//only write模式下打开文件 没有该文件则创建
if ((fp = fopen("./work.txt","w")) == NULL)
{
perror("fopen");
return -1;
}
//在文件中写入数据
fputs("hello world\n",fp);
fputs("hello china\n",fp);
fputs("hello sahnghai\n",fp);
//关闭
if (fclose(fp) != 0)
{
perror("fclose");
return -1;
}
/***************************************************************/
//only read模式下打开文件
if ((fp = fopen("./work.txt","r")) == NULL)
{
perror("fopen");
return -1;
}
char buf[5];
char *p = NULL;
int count = 1;
while (fgets(buf,sizeof(buf),fp) != NULL)
{
p = buf;
while (*p)
{
if (*p!='\n')
{
p++;
}else{
count++;
break;
}
}
}
printf("%d\n",count);
//关闭
if (fclose(fp) != 0)
{
perror("fclose");
return -1;
}
return 0;
}
文件拷贝 使用fputs()
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, const char *argv[])
{
FILE *fp_r = NULL;
FILE *fp_w = NULL;
if ((fp_r = fopen("./work.txt","r")) == NULL)
{
perror("fopen");
return -1;
}
if ((fp_w = fopen("./copy.txt","w")) == NULL)
{
perror("fopen");
return -1;
}
char buf[5];
char *p = NULL;
int count = 1;
while (fgets(buf,sizeof(buf),fp_r) != NULL)
{
fputs(buf,fp_w);
}
if (fclose(fp_r) != 0)
{
perror("fclose");
return -1;
}
if (fclose(fp_w) != 0)
{
perror("fclose");
return -1;
}
return 0;
}