C 庫 - fputs() 函式



C 庫 int fputs(const char *str, FILE *stream) 函式將字串寫入指定的流,直到但不包括空字元。它通常用於將文字寫入檔案。

語法

以下是 C 庫 fputs() 函式的語法:

int fputs(const char *str, FILE *stream);

引數

此函式接受兩個引數:

  • const char *str: 指向要寫入檔案的以空字元結尾的字串的指標。
  • FILE *stream: 指向 FILE 物件的指標,該物件標識要寫入字串的流。該流可以是開啟的檔案或任何其他標準輸入/輸出流。

返回值

成功時,fputs 返回非負值。發生錯誤時,它返回 EOF (-1),並且流的錯誤指示器被設定。

示例 1:將字串寫入檔案

此示例將簡單的字串寫入文字檔案。

以下是 C 庫 fputs() 函式的示例。

#include <stdio.h>

int main() {
    FILE *file = fopen("example1.txt", "w");
    if (file == NULL) {
        perror("Failed to open file");
        return 1;
    }
    
    if (fputs("Hello, World!\n", file) == EOF) {
        perror("Failed to write to file");
        fclose(file);
        return 1;
    }
    
    fclose(file);
    return 0;
}

輸出

以上程式碼開啟一個名為 example1.txt 的檔案以進行寫入,將“Hello, World!”寫入其中,然後關閉該檔案。

Hello, World!

示例 2:將多行寫入檔案

此示例使用迴圈中的 fputs 將多行寫入檔案。

#include <stdio.h>

int main() {
    FILE *file = fopen("example3.txt", "w");
    if (file == NULL) {
        perror("Failed to open file");
        return 1;
    }
    
    const char *lines[] = {
        "First line\n",
        "Second line\n",
        "Third line\n"
    };
    
    for (int i = 0; i < 3; ++i) {
        if (fputs(lines[i], file) == EOF) {
            perror("Failed to write to file");
            fclose(file);
            return 1;
        }
    }
    
    fclose(file);
    return 0;
}

輸出

執行以上程式碼後,它透過迭代字串陣列並在每次迭代中使用 fputs 將三行不同的內容寫入 example3.txt。

First line
Second line
Third line
廣告