/***
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結束的話不能輸出到檔案中。
#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;
}