C語言:檔案(4)fgets和fputs。
阿新 • • 發佈:2021-02-01
文字行輸入函式 fgets
#include<stdio.h>
int main()
{
char arr[1024] = { 0 };
FILE* f = fopen("text.txt", "r");
if (f==NULL)
{
return 0;
}
//讀檔案
fgets(arr, 1024, f);//fgets每次列印一行,列印時會自動換行。
//arr儲存的位置,1024為arr的最大容量,f為儲存的檔案指標
printf("%s", arr);//列印abc
fgets (arr, 1024, f);
puts(arr);//列印hello, puts也會自動換行
fclose(f);
f = NULL;
return 0;
}
文字行輸出函式 fputs
#include<stdio.h>
int main()
{
FILE* f = fopen("text.txt", "w");
if (f==NULL)
{
return 0;
}
fputs("hello", f);//不會自動換行
fputs("world", f);
fclose(f);
f = NULL;
return 0;
}
fputs("hello\n", f);
fputs("world\n", f);
#include<stdio.h>
//從鍵盤上讀取,在螢幕上顯示。
int main()
{
char arr[1024] = { 0 };
FILE* f = fopen("text.txt", "r");
if (f == NULL)
{
return 0;
}
//從標準輸入流讀取
fgets(arr, 1024, stdin);//===gets(arr);
//輸出到標準輸出流
fputs(arr, stdout); //===puts(arr);
return 0;
}