读书人

c,该如何处理

发布时间: 2012-03-05 11:54:02 作者: rapoo

c

C/C++ code
#include<stdio.h>#include<stdlib.h>#include<string.h>void main(){    char str[10];    FILE *fp;    if((fp=fopen("123.txt","wr"))==NULL)    {        printf("cann't open file\n");        exit(0);    }    do    {        printf("please enter a string:");        gets(str);        strcat(str,"\n");        fputs(str,fp);    }    while(*str!='\n');    //    rewind(fp);    while(!feof(fp))    {        fgets(str,9,fp);        printf("%s",str);    }    fclose(fp);}


[解决办法]
if((fp=fopen("123.txt","wr"))==NULL)
改为
if((fp=fopen("123.txt","w+"))==NULL)/*创建并读写,如果存在覆盖*/

if((fp=fopen("123.txt","r+"))==NULL)/*打开已存在文件,并读写*/
[解决办法]
C/C++ code
#include<stdio.h>#include<stdlib.h>#include<string.h>int main(){    char str[10];    FILE *fp;    if((fp=fopen("123.txt","w+"))==NULL)//就修改了这里,用w+创建并读写    {        printf("cann't open file\n");        system("pause");        exit(0);    }    do    {        printf("please enter a string:");        gets(str);        strcat(str,"\n");        fputs(str,fp);    }    while(*str!='\n');    //    rewind(fp);    while(!feof(fp))    {        fgets(str,9,fp);        printf("%s",str);    }    fclose(fp);        system("pause");    return 0;} 

读书人网 >C语言

热点推荐