利用fetc读取字符,fputc写入字符,实现文件的拷贝:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp1;
FILE *fp2;
int ch;
if ((fp1 = fopen("hello.txt", "r")) == NULL)
{
printf("文件打开失败!\n") ;
exit(EXIT_FAILURE);
}
if ((fp2 = fopen("fishc.txt","w")) == NULL)
{
printf("文件打开失败!\n");
exit(EXIT_FAILURE);
}
while ((ch = fgetc(fp1)) != EOF)
{
fputc(ch, fp2);
}
fclose(fp1);
fclose(fp2);
return 0;
}
读写字符串
#include <stdio.h>
#include <stdlib.h>
#define MAX 1024
int main(void)
{
FILE *fp;
char buffer[MAX];
if ((fp = fopen("lines.txt", "w")) == NULL)
{
printf("打开文件失败!\n");
exit("EXIT_FAILURE");
}
fputs("Line one: Hello you!\n", fp);
fputs("Line two: Hello home!\n", fp);
fputs("Line three: Hello world!\n", fp);
fclose(fp);
if ((fp = fopen("lines.txt", "r")) == NULL)
{
printf("打开文件失败!\n");
exit("EXIT_FAILURE");
}
while(!feof(fp))
{
fgets(buffer, MAX, fp);
printf("%s", buffer);
}
return 0;
}