簡體   English   中英

使用 fgets() 從終端寫入文件文本

[英]Write to file text from terminal using fgets()

#include <stdio.h> 
#include <cstdio>
int main(int argc, char* argv[]) {
    char buff[512];
    int desc;
    int lb;
    desc = open(argv[1], O_WRONLY);
    if(desc == -1) {
        perror("error");
        exit(1);
    }
    while(lb=fgets(buff,512,stdin) > 0) {
        write(desc,buff,lb);

    }
    
}

在 linux 上的 C 中,我必須使用 fgets() 從用戶編寫的終端寫入作為 argv 文本傳遞的文件。程序應該在循環中工作,如果用戶寫“結束”程序停止。 我猜現在程序將從標准輸入寫入文件文本,不確定如何在“結束”條件下結束程序。

“不太確定如何從終端獲取文本到緩沖區”

fopen()是一個更好的選擇(根據open()的評論)。 以下假設是一個文本文件,並且命令行上有一個有效的文件規范 它將讀取直到它看到“結束”,然后將其捕獲為最后一行......

(也將在以下情況下退出:對於 UNIX 系統Ctrl + D或 Windows Ctrl + Z 。)

#define INSTRUCTIONS "Entered text will be written to file %s.\n\
When finished with desired input press '<enter>end'.\n\
This will close and save the file, and exit the program.\n\
Begin Here:\n"
 

int main(int argc, char *argv[])
{
    char buffer[80] = {0};
    if(argv < 1) 
    {
        printf("missing filespec in command line\nHit any key to exit.");
        getchar();
        return 0;
    }
    printf(INSTRUCTIONS, argv[1]);
    FILE *fp = fopen(argv[1], "w");
    if(fp)
    {
        while(fgets(buffer, sizeof buffer, stdin))//reads until EOF
        {
            fputs(buffer, fp);
            buffer[strcspn(buffer, "\n")] = 0;//clear newline
            //looks for a new line containing only end\n
            if(strcmp(buffer, "end") == 0)
            {
                fclose(fp);
                break;
            }
        }
    }
    return 0;
}
    

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM