您的位置:首页 > 其它

关于读写文件的操作

2013-11-08 12:07 155 查看
program1.写文件

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

int main()

{

FILE *fp;

char ch;

if((fp=fopen("test2.txt","wt"))==NULL)

{

printf("Cannot open file!\n");

getch();

exit(1);

}

printf("Please input a character:");

//ch=getchar();

/* while(ch!='\n')

{

fputc(ch,fp);

putchar(ch);

ch=getchar();

}*/

while((ch=getchar())!='\n')

{

fputc(ch,fp);

}

//以下两个fputc()用于连接文件时换行

//fputc( '\r', fp );

// fputc( '\n', fp );

fclose(fp);

system("pause");

return 0;

}

program2.读文件

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

int main()

{

FILE *fp;

char ch;

if((fp=fopen("test2.txt","rt"))==NULL)

{

printf("Cannot open file!\n");

getch();

exit(1);

}

printf("Please input a character:\n");

//ch=fgetc(fp);

while((ch=fgetc(fp))!=EOF)

{

putchar(ch);

}

fclose(fp);

printf("\n");

system("pause");

return 0;

}

program3.读写合并文件

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

int main()

{

FILE *fp,*fp1,*fp2;

char ch;

if((fp=fopen("test3.txt","wt"))==NULL)

{

printf("Cannot open file!\n");

getch();

exit(1);

}

printf("The file test.txt is open!\n");

if((fp1=fopen("test1.txt","rt"))==NULL)

{

printf("Cannot open file!\n");

getch();

exit(1);

}

printf("The file test1.txt is open!\n");

if((fp2=fopen("test2.txt","rt"))==NULL)

{

printf("Cannot open file!\n");

getch();

exit(1);

}

printf("The file test2.txt is open!\n");

while((ch=fgetc(fp1))!=EOF)

{

fputc(ch,fp);

}

fputc( '\n', fp );

while((ch=fgetc(fp2))!=EOF)

{

fputc(ch,fp);

}

/*

fclose(fp1);

fclose(fp2);

fclose(fp);

*/

_fcloseall(); //fcloseall(); 用不了

printf("文件合并完成!\n");

system("pause");

return 0;

}

program1运行结果:

test2.txt

ABCDEFGHJ

若有

test1.txt

abcefghjk

program3运行结果:

test3.txt

ABCDEFGHJ

abcefghjk

如果再program3程序的两个读操作之间不加语句 fputc( '\n', fp ); ,则 program3运行结果为

test3.txt

ABCDEFGHJabcefghjk
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: