求c语言编程文件操作实例!

如题所述

1.打开一个文件

#include <stdio.h>
main()
{
FILE *fp; /*定义一个文件指针*/
int i;
fp=fopen("wenjian", "rb"); /*打开当前目录名为wenjian的文件只读*/
if(fp==NULL) /*判断文件是否打开成功*/
puts("File open error");/*提示打开不成功*/
i=fclose(fp); /*关闭打开的文件*/
if(i==0) /*判断文件是否关闭成功*/
printf("O,K"); /*提示关闭成功*/
else
puts("File close error");/*提示关闭不成功*/
}

2.运行后产生一个text.dat的文件
#include<stdio.h>
main()
{
char *s="That's good news"); /*定义字符串指针并初始化*/
int i=617; /*定义整型变量并初始化*/
FILE *fp; /*定义文件指针*/
fp=fopne("test.dat", "w"); /*建立一个文字文件只写*/
fputs("Your score of TOEFLis", fp);/*向所建文件写入一串字符*/
fputc(':', fp); /*向所建文件写冒号:*/
fprintf(fp, "%d\n", i); /*向所建文件写一整型数*/
fprintf(fp, "%s", s); /*向所建文件写一字符串*/
fclose(fp); /*关闭文件*/
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2018-05-01
/**************************************************/
/* 文件的字符形式读取与存储和字符串形式的读取与存储 */
/**************************************************/

/*读一个字符*/
#include "stdio.h"
#include "string.h"
main(){
FILE *fp;
char c;
if((fp=fopen("s.c","r"))==NULL){
printf("\nFile can not open!");
getch();
exit(0);
}
while(!feof(fp)){
c=fgetc(fp);
putchar(c);
}
fclose(fp);
getch();
}
/*写一个字符*/
#include "stdio.h"
#include "string.h"
main(){
FILE *fp;
char c;
if((fp=fopen("d:\\data.txt","w"))==NULL){
printf("\nFile can not open!");
getch();
exit(0);
}
while((c=getchar())!='#'){
fputc(c,fp);
}
fclose(fp);
}
/*读写字符串*/
#include "stdio.h"
#include "string.h"
main(){
FILE *fp;
char c[80]={""},s[80]={""};
/*写字符串*/
if((fp=fopen("d:\\data.txt","w"))==NULL){
printf("\nFile can not open!");
exit(0);
}
gets(c);
fputs(c,fp);
fclose(fp);
/*读字符串*/
if((fp=fopen("d:\\data.txt","r"))==NULL){
printf("\nFile can not open!");
exit(0);
}
while(!feof(fp)){
fgets(s,80,fp);
puts(s);
}
fclose(fp);
getch();
}

你看这个可以吗 不行我再改改!本回答被网友采纳
相似回答