1、使用fgets统计给定文件的行号
代码:
/*******************************************/
文件名:io1.c
/*******************************************/
#include <myhead.h>
int main(int argc, char const *argv[])
{
//判断是否导入了一个要引用的文件
if (argc != 2)
{
printf("input file error\n");
printf("usage:./a.out filename\n");
return -1;
}
//定义文件指针
FILE *fp = NULL;
if ((fp = fopen(argv[1], "r")) == NULL)
{
perror("fopen error");
return -1;
}
//定义数组接收数据
char buf[64] = "";
//定义整型表示行数
int num = 0;
int num_keep[100] = {0};
while (1)
{
bzero(buf, sizeof(buf));
if (fgets(buf, sizeof(buf), fp) == NULL)
{
break;
}
//定义整型获取每行真实长度
int len = strlen(buf);
//判断是否有'\n'分行
if (buf[len - 1] == '\n')
{
num++;
}
num_keep[num - 1] = num;
}
printf("该文件共有%d行\n", num);
printf("该文件的行号分别为:\n");
for (int i = 0; num_keep[i] != 0; i++)
{
printf("%d\t", num_keep[i]);
}
printf("\n");
//关闭文件指针
fclose(fp);
return 0;
}
结果:
2、使用fgets、fputs完成两个文件的拷贝
代码:
/*******************************************/
文件名:io2.c
/*******************************************/
#include <myhead.h>
int main(int argc, char const *argv[])
{
if (argc != 3)
{
printf("input file error\n");
printf("usage:./a.out srcfile destfile\n");
return -1;
}
FILE *sfp = fopen(argv[1], "r+");
if (sfp == NULL)
{
printf("open srcfile error\n");
return -1;
}
FILE *dfp = fopen(argv[2], "w");
if (dfp == NULL)
{
printf("open destfile error\n");
fclose(sfp);
return -1;
}
// 写入数据到sfp
fputs("Hello World!\n", sfp);
fputs("Welcome to China\n", sfp);
fputs("We are friends!\n", sfp);
fputs("HaHaHaHa!\n", sfp);
fputs("See you!\n", sfp);
// 移动文件指针到文件开始
rewind(sfp);
// 读取sfp并写入dfp
char buf[40] = "";
while (fgets(buf, sizeof(buf), sfp) != NULL)
{
fputs(buf, dfp);
}
// 关闭文件
fclose(sfp);
fclose(dfp);
// 重新打开文件进行读取
sfp = fopen(argv[1], "r");
if (sfp == NULL)
{
printf("open srcfile error\n");
return -1;
}
printf("sfp中的内容为:\n");
char bufn[20];
while (fgets(bufn, sizeof(bufn), sfp) != NULL)
{
printf("%s", bufn);
}
fclose(sfp);
// 检查dfp是否需要重新打开进行读取
dfp = fopen(argv[2], "r");
if (dfp == NULL)
{
printf("open srcfile error\n");
return -1;
}
printf("dfp中的内容为:\n");
char bufm[20];
while (fgets(bufm, sizeof(bufm), sfp) != NULL)
{
printf("%s", bufm);
}
return 0;
}