簡體   English   中英

C中的fgets函數和文件處理

[英]fgets function and file handling in C

我正在嘗試制作一個程序,該程序將用戶輸入的數據存儲在名稱由用戶提供的文本文件中。 當用戶進入出口時程序將終止。 string.h的strcmp函數用於字符串比較,而fgets()用於從stdin讀取數據。

這是我的代碼。

#include<stdio.h>
#include<string.h>

void main()
{
    char file[60];          // will store file name
    printf("Enter file name: ");
    fgets(file, 59, stdin);

    FILE *fp = fopen(file, "a+");   // open file in append mode

    if(fp == NULL){
        printf("File not found !");
        return;
    }

    char data[100];
    printf("Enter some data to add to file(exit to terminate): ");
    fgets(data, 99, stdin);

    int flag = strcmp(data, "exit");

    while(flag != 0){
        fputs(data, fp);

        fgets(data, 59, stdin);
        flag = strcmp(data, "exit");
        printf("%d\n", flag);       // for checking whether string are correctly comapred or not
    }

    printf("Bye");

}

即使我進入出口,程序也不會終止。 我也嘗試在用戶輸入的字符串末尾連接“ \\ n”,但這也無濟於事。 雖然gets()函數可以正常工作,但我知道使用fgets()並不是首選,但是它對我不起作用。

檢查手冊頁中的fgets() ,它在輸入后讀取並存儲換行符(按ENTER引起)。 因此, strcmp()失敗。

在比較輸入之前,必須手動從換行符中除去輸入緩沖區。 一個簡單而優雅的方法是

 data[strcspn(data, "\n")] = 0;

fgets讀取完整的“行”,即一系列字符,直到(包括!)換行符為止。 因此,當用戶按下“ Enter”鍵時,新行將成為讀入字符串的一部分,並且strcmp(data,"exit")評估結果為“不等於”。

因此,要么在比較之前刪除新行,要么與包含新行的字符串文字進行比較。 由於您將數據原樣(即包括新行)寫入文件,因此先剝離新行並手動添加然后將其添加到輸出中似乎很麻煩。 所以我實際上建議第二種方法:

fgets(data, 100, stdin);
flag = strcmp(data, "exit\n");

如果多余的字符無關緊要,則可以使用strstr (即,如果用戶鍵入“ exit”或“ asdfexitasdf”,則程序將退出-兩者都包含“ exit”。)

所以

int flag = strstr(data, "exit");
if(flag != NULL)
    //exit the program
else
    //stay in the program

暫無
暫無

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

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