C語言fputs()和fgets()函數

在C語言編程中,fputs()fgets()函數用於從流中寫入和讀取字串。下麵來看看看如何使用fgets()fgets()函數寫和讀檔的例子。

寫檔:fputs()函數

fputs()函數將一行字串寫入檔,它將字串輸出到流。

fputs()函數的語法:

int fputs(const char *s, FILE *stream)

示例:

創建一個原始檔案:fputs-write-file.c,其源代碼如下 -

#include<stdio.h>
void main() {
    FILE *fp;

    fp = fopen("myfile2.txt", "w");
    fputs("hello c programming \n", fp);
    fputs("zaixian tutorials c programming \n", fp);
    printf("all content had write to file: myfile2.txt\n");
    fclose(fp);
}

執行上面示例代碼,得到以下結果 -

all content had write to file: myfile2.txt

執行上面代碼後,打開檔:myfile2.txt,應該會看到以下內容 -

hello c programming
zaixian tutorials c programming

讀取檔:fgets()函數

fgets()函數從檔中讀取一行字串,它從流中獲取字串。

語法:

char* fgets(char *s, int n, FILE *stream)

示例:

創建一個原始檔案:fgets-read-file.c,其代碼如下所示 -

#include<stdio.h>

void main() {
    FILE *fp;
    char text[300];

    fp = fopen("myfile2.txt", "r");
    printf("%s", fgets(text, 200, fp)); // 第一行

    printf("%s", fgets(text, 200, fp)); // 第二行

    fclose(fp);
}

執行上面示例代碼,得到以下結果 -

hello c programming
zaixian tutorials c programming

上一篇: C語言fputc()和fgetc()函數 下一篇: C語言fseek()函數