将键盘上输入的一个字符串保存到一个磁盘文件中。。c语言编写

跪求大神

fwrite、fprintf、fputc等写文件函数都可以完成,而专用的字符串文件写入函数fputs更方便一些。举例如下(文件建立在当前目录下,名为123.txt):

//#include "stdafx.h"//If the vc++6.0, with this line.
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
int main(void){
    char s[70];
    FILE *fp;
    if((fp=fopen("123.txt","w"))==NULL){
        printf("Open the file failure...\n");
        exit(0);
    }
    while(1){
        printf("Input a string...\ns=");
        if(gets(s),strlen(s)<70)
            break;
        printf("Too long, redo: ");
    }
    fputs(s,fp);
    fclose(fp);
    printf("\n");
    return 0;
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-12-16
使用fopen() fwrite() 等函数,详细可以参考c/c++标准库。下面是一个示例代码,向1.txt中写入20字节的字串。

#include <stdio.h>
int main()
{
char str[20] = "testtesttesttesttes";
FILE *fp = fopen("1.txt", "w+");
if (fp==0) {
printf("can't open file\n");
return 0;
}
fwrite(str, sizeof(char)*20, 1, fp);
fclose(fp);
return 0;
}追问

char str[20] = "testtesttesttesttes"后面的testtest可以省略吧

追答

本回答被提问者采纳
第2个回答  2013-07-05
#include<stdio.h>

void main()
{
char str[200];
FILE *fp;
printf("请输入一个字符串:\n");
gets(str);
if((fp=fopen("test.txt","wt"))==NULL)
{
printf("cannot open file\n");
return;
}
fprintf(fp,"%s",str);
fclose(fp);
}
相似回答