目录
1. 用fgetc和fputc实现,拷贝一个文件,例如将1.c的内容拷贝给2.c
3. 用fgetc计算一个文件有几行,要求封装成函数(linux操作系统以\n结尾,就算是最后一行也 有一个'\n')
4. 用fgets和fputs实现,拷贝一个文件,例如将1.c的内容拷贝给2.c
6. 用fgets计算一个文件有几行,要求封装成函数(linux操作系统以\n结尾,就算是最后一行也 有一个'\n')
1. 用fgetc和fputc实现,拷贝一个文件,例如将1.c的内容拷贝给2.c
函数代码:
#include<stdio.h>
int main(int argc, const char *argv[])
{
FILE *fp = fopen("./123.txt","w");
if(fp == NULL)
{
printf("文件打开失败\n");
perror("fopen");
return -1;
}
printf("打开成功\n");
fputc('A',fp);
fputc('B',fp);
fputc('C',fp);
if(fclose(fp) < 0)
{
printf("flose is failed\n");
perror("fclose");
return -1;
}
printf("fclose success\n");
fp = fopen("./123.txt","a+");
FILE *p=fopen("./456.txt","w");
char c = 0;
while((c = fgetc(fp)) != EOF)
{
fputc(c,p);
}
fclose(fp);
return 0;
}
执行结果:
2. 用fgetc计算一个文件的大小,要求封装成函数
函数代码:
#include<stdio.h>
void my_sizeof(FILE *fp)
{
char c = 0;
int count = 0;
while((c = fgetc(fp)) != EOF)
{
count++;
}
printf("这个文件的大小为:%d\n",count);
}
int main(int argc, const char *argv[])
{
FILE *fp = fopen("./a.txt","w");
if(fp == NULL)
{
perror("fopen");
return -1;
}
fputc('a',fp);
fputc('b',fp);
fputc('c',fp);
fputc('d',fp);
fputc('e',fp);
fclose(fp);
fp = fopen("./a.txt","r");
my_sizeof(fp);
fclose(fp);
return 0;
}
执行结果:
3. 用fgetc计算一个文件有几行,要求封装成函数(linux操作系统以\n结尾,就算是最后一行也 有一个'\n')
函数代码:
#include<stdio.h>
void line_sum(FILE *fp)
{
char c = 0;
int count = 0;
while((c = fgetc(fp)) != -1)
{
if(c == '\n')
{
count++;
}
}
printf("这个文件有 %d 行\n",count);
}
int main(int argc, const char *argv[])
{
FILE *fp = fopen("line.txt","r");
if(fp == NULL)
{
perror("fopen");
return -1;
}
line_sum(fp);
fclose(fp);
return 0;
}
执行结果:
4. 用fgets和fputs实现,拷贝一个文件,例如将1.c的内容拷贝给2.c
函数代码:
#include<stdio.h>
int main(int argc, const char *argv[])
{
FILE *fp = fopen("copy.txt","r");
if(fp == NULL)
{
perror("fopen");
return -1;
}
fputs("hello world",fp);
FILE *p = fopen("copy2.txt","w");
char str[20] = "";
while(fgets(str,sizeof(str),fp) != NULL)
{
fputs(str,p);
// fflush(fp);
}
fclose(fp);
fclose(p);
return 0;
}
执行结果:
5. 用fgets计算一个文件的大小,要求封装成函数
函数代码:
#include<stdio.h>
#include<string.h>
void my_sizeof(FILE *fp)
{
char str[20] = "";
fgets(str,sizeof(str),fp);
int len = strlen(str);
printf("这个文件的大小为:%d",len);
}
int main(int argc, const char *argv[])
{
FILE *fp = fopen("size.txt","r");
if(fp == NULL)
{
perror("fopen");
return -1;
}
my_sizeof(fp);
fclose(fp);
return 0;
}
执行结果:
6. 用fgets计算一个文件有几行,要求封装成函数(linux操作系统以\n结尾,就算是最后一行也 有一个'\n')
函数代码:
#include<stdio.h>
#define N 50
void line_sum(FILE *fp)
{
int count = 0;
char str[N] = "";
while(fgets(str,sizeof(str),fp) != NULL)
{
for(int i=0;i<sizeof(str);i++)
{
if(str[i] == '\n')
{
count++;
}
}
}
printf("这个文件有 %d 行\n",count);
}
int main(int argc, const char *argv[])
{
FILE *fp = fopen("789.txt","r");
if(fp == NULL)
{
perror("fopen");
return -1;
}
line_sum(fp);
fclose(fp);
return 0;
}
执行结果: