要求:
1.使用fgets统计文件的行号
2.使用fgets/fputs拷贝文件
思路:
1.在./a.out后输入一个文件进行统计该文件行号
2.在./a.out后输入两个文件进行复制第一个文件拷贝到第二个文件中。当第二个文件不存在时创建第二个文件并进行拷贝。
源代码如下:
main.c
#include <head.h>
#include "homework.h"
int main(int argc, const char *argv[])
{
FILE *fp, *fp1;
int a = argc;
if (a == 2)
{
if ((fp = fopen(argv[1], "r")) == NULL)
PRINT_ERR("打开文件失败");
line_file(a, fp);
}
else if (a == 3)
{
if ((fp = fopen(argv[1], "r")) == NULL)
PRINT_ERR("打开文件失败");
if ((fp1 = fopen(argv[2], "a")) == NULL)
PRINT_ERR("打开文件失败");
copy_file(a, fp, fp1);
}
return 0;
}
head.h
#ifndef __HEAD_H__
#define __HEAD_H__
#include <stdio.h>
#include <errno.h>
#include <string.h>
#define PRINT_ERR(msg) \
do{ \
perror(msg); \
return -1; \
}while(0)
#endif
work.c
#include <head.h>
int copy_file(int a, FILE *fp, FILE *fp1)
{
char buffer[10];
if (a != 3)
{
printf("input error,try again\n");
printf("usage:./a.out filename filename\n");
return -1;
}
while ((fgets(buffer, sizeof(buffer), fp)) != NULL)
{
fputs(buffer, fp1);
}
fclose(fp);
fclose(fp1);
return 0;
}
int line_file(int a, FILE *fp)
{
int num = 0;
char buffer[10];
if (a != 2)
{
printf("input error,try again\n");
printf("usage:./a.out filename\n");
return -1;
}
while ((fgets(buffer, sizeof(buffer), fp)) != NULL)
{
if (buffer[strlen(buffer) - 1] == '\n')
{
num++;
}
}
printf("该文件有%d行\n", num);
fclose(fp);
return 0;
}
work.h
#ifndef __HOMEWORK_H__
#define __HOMEWORK_H__
int copy_file(int a, FILE *fp, FILE *fp1);
int line_file(int a, FILE *fp);
#endif