簡體   English   中英

如何在 fgets() 中故意觸發錯誤?

[英]How do I intentionally trigger an error in fgets()?

概括

使用fgets() ,我有錯誤檢查代碼,可以在fgets()返回null但尚未到達文件末尾時執行一些補救措施。 我想練習這部分代碼以驗證它是否按預期工作。

是否有觸發fgets()失敗的規范方法? 通過手動方式(以某種方式在調用fgets()之間刪除文件),一些測試設置(提供故意“損壞”的文件),還是其他方式?


最小可重復示例

fgets_fail_test.cpp:

// Test code to show minimally reproducible example of fgets() error handling
// The desire is to manually trigger a failure in fgets()

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

int main(int argc, char **argv) {
    FILE *fp = fopen("test_file.txt", "r"); //assume this works, not testing this
    char buf[100]; //assume large enough to hold data
    unsigned int lineno = 1;

    while (fgets(buf, 100, fp)) {
        std::cout << buf;
        lineno++;
    }

    if (feof(fp)) {
        std::cout << "End of file encountered.\n";
    }
    else if (ferror(fp)) { // how do I trigger an fgets error to cause this to return true?
        printf("Encountered read error at line no %u. Error: %d, %s.\n",
               lineno,
               errno,
               strerror(errno));
    }

    fclose(fp); // assume this works, not testing this

    return 0;
}

測試文件.txt:

ABCDEFG
HIJKLMN
OPQRSTU
VWXYZ
The quick brown fox
jumped over the
lazy dog.
Goodbye.

理論

雖然我可以簡單地用一些測試腳手架替換有問題的代碼(編寫一個保持內部狀態的 fgets 包裝器,增加一個計數器,一旦它到達第 #N 行,它就返回null並手動設置文件錯誤和 errno)我覺得應該是一些“內置”的方式來做到這一點?

如果唯一的解決方案是腳手架,我會這樣做。 老實說,也許我在這里太聰明了。

在一些相關和鏈接的問題中給出了很多好的答案,這可能會使我的問題重復。 雖然我在最初搜索時專注於fgets() ,但我無法找到這些。

一些相關的問題是:

因為我的程序從具有給定文件名格式的已知文件列表中讀取數據,所以我需要使用一種方法來向程序提供錯誤文件(無需修改代碼)。 我決定使用這個答案來做到這一點。

方法

為了生成會觸發fgets()讀取失敗的錯誤文件,我利用了/proc/self/mem的“功能”,即讀取它會導致 I/O 錯誤。

我刪除了舊輸入文件,並將舊名稱下的新文件鏈接到/proc/self/mem

ln -s /proc/self/mem test_file.txt

運行該文件然后產生以下輸出:

Encountered read error at line no 1. Error: 5, Input/output error.

表明我們觸發了錯誤。 感謝@Artyer 的評論,他們最初將我與相關問題聯系起來。

暫無
暫無

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

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