#include <myhead.h>
int main(int argc, const char *argv[])
{
if(argc!=3)
{
printf("外部参数错误\n");
return -1;
}
FILE *fp1 = fopen("./1.txt","r");
if(NULL==fp1)
{
perror("fp1");
return -1;
}
FILE *fp2 = fopen("./2.txt","w");
if(NULL==fp2)
{
perror("fp2");
return -1;
}
while(10)
{
char buff = fgetc(fp1);
if(buff==EOF)
{
break;
}
fputc(buff,fp2);
}
fclose(fp1);
fclose(fp2);
printf("拷贝成功\n");
fp2 = fopen("./2.txt","r");
if(NULL==fp2)
{
perror("fp2");
return -1;
}
while(10)//循环输出
{
char arr = fgetc(fp2);
if(arr==EOF)
{
break;
}
fputc(arr,stdout);
}
fclose(fp2);
return 0;
}
作业:fgets获取文件的行号
#include <myhead.h>
int main(int argc, const char *argv[])
{
FILE *fp = fopen("./1.txt","r");
if(fp==NULL)
{
perror("fopen");
return -1;
}
int count =0;
char buff[100];//存放读取的字符串
while(fgets(buff,sizeof(buff),fp)!=NULL)//读取文件内的字符串
{
if (buff[strlen(buff)-1] == '\n')
{
count++;
}
}
printf("有%d行\n",count);//读取完输出
fclose(fp);
return 0;
}
fgets和fputs拷贝文件
#include <myhead.h>
int main(int argc, const char *argv[]) {
FILE *fp1 = fopen("1.txt", "r");
if (fp1== NULL) {
perror("fopen");
return -1;
}
FILE *fp2 = fopen("2.txt", "w");
if (fp2 == NULL) {
perror("fopen");
fclose(fp1);
return -1;
}
char buff[100];
while (fgets(buff, sizeof(buff), fp1) != NULL) { // 从源文件逐行读取
fputs(buff, fp2); // 将读取的内容写入目标文件
}
fclose(fp1); // 关闭源文件
fclose(fp2); // 关闭目标文件
fp2 = fopen("2.txt", "r");
if (fp2 == NULL) {
perror("fopen");
return -1;
}
char arr[100];
while (fgets(arr, sizeof(arr), fp2) != NULL) {
printf("%s", arr);
}
fclose(fp2);
return 0;
}