/*** file.c ***/ #include<stdio.h>int main() {//用寫的方式打開一個文件 //w的意思是文件如果不存在,就建立一個文件,如果文件存在就覆蓋FILE *p = fopen("/home/exbot/wangqinghe/C/20190716/file1.txt","w");fputs("hello world\n",p); //向文件中寫入一個字符串fclose(p); //關閉這個文件return 0; }
/*** file1.txt ***/ #include<stdio.h> #include<string.h> int main() {char s[1024] = {0};FILE *p = fopen("/home/exbot/wangqinghe/C/20190716/file1.txt","w");while(1){memset(s,0,sizeof(s));scanf("%s",s);if(strcmp(s,"exit") == 0){break;}int len = strlen(s);s[len] = '\n';fputs(s,p);}fclose(p);return 0; }
缺陷:scanf輸入會將空格自動隔開下一行。
gcc已經禁止使用gets函數了。
接受帶空格的字符出的方法,vs中可以使用gets_s函數,
linux環境下只能使用char *fgets(char *buf, int bufsize, FILE *stream);
fget(str,maxn,stdin); stdin表示接受從鍵盤中輸入。
但是fgets輸入是在緩沖區中讀入的,不能接受在輸入的時候判斷輸入的字符串來中斷循環。
#include<stdio.h> #include<string.h> #include<stdlib.h> const int maxn = 1024; int main() {char s[1024] = {0};FILE *p = fopen("/home/exbot/wangqinghe/C/20190716/file1.txt","w");while(fgets(s,maxn,stdin) != EOF){printf("s = %s\n",s);fputs(s,p);}fclose(p);return 0; }
可以輸入到字符串中并打印出來,但是手動結束ctrl+v結束的話不能輸出到文件中。
?
還可以使用scanf(“%[^\n]”,str);來實現這個功能
#include<stdio.h> #include<string.h> #include<stdlib.h> const int maxn = 10; int main() {char s[1024] = {0};FILE *p = fopen("/home/exbot/wangqinghe/C/20190716/file1.txt","w");while(1){//memset(s,0,sizeof(s));scanf("%[^\n]",s);if(strcmp(s,"exit") == 0)break;printf("s = %s\n",s);fputs(s,p);}fclose(p);return 0; }
有問題,待解決。