[英]Ncurses program is exiting without even creating a window
我寫了一個簡單的C抽認卡程序; 它將文件名作為第二個參數,然后逐行讀取該文件並使用 ncurses,向用戶顯示問題,按回車鍵顯示答案,再次按刷新 ncurses window 以便下一個行被讀取。 讀取的文件是一個簡單的 TSV(盡管我已經編寫了它以便它可以是任何分隔符)。 這是文件,標題為f.c :
注意:我使用了 readline(),一個非 C 標准的 function,因為這是一個我只會在 POSIX 系統上使用的個人項目,所以用 fgets 正確管理 memory 的頭痛是不值得的
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ncurses.h>
#include <unistd.h>
#include <errno.h>
#define DELIM "\t"
int count_occ(char* string, char* val)
{
int count = 0;
const char* tmp = string;
while(tmp = strstr(tmp, val))
{
count++;
tmp++;
}
return count;
}
bool valid_file(FILE* stream)
{
char* line = NULL;
size_t len;
while(getline(&line, &len, stream) != -1)
{
if(count_occ(line, DELIM) != 1)
{
return false;
}
}
return true;
}
int main(int argc, char* argv[])
{
if(argc != 2)
{
fprintf(stderr, "File name must be supplied\n");
exit(EXIT_FAILURE);
}
if(!access(argv[1], F_OK) == 0)
{
fprintf(stderr, "File supplied in second argument does not exist\n");
exit(EXIT_FAILURE);
}
FILE* stream = fopen(argv[1], "r");
if(!valid_file(stream))
{
fprintf(stderr, "File supplied is not properly formatted: a line is missing a set of delimited values or too many fields were noticed\n");
exit(EXIT_FAILURE);
}
initscr();
noecho();
raw();
char* line = NULL;
size_t len;
while(getline(&line, &len, stream) != -1)
{
char* qn = strtok(line, DELIM);
char* ans = strtok(NULL, DELIM);
char c;
printw("Question:\n\t%s\nAnswer:\n\t...\n\n", qn);
while((c = getch()) != 10);
refresh();
move(0, 0);
printw("Question:\n\t%s\nAnswer:\n\t%s\n\n", qn, ans);
while((c = getch()) != 10);
refresh();
move(0, 0);
}
endwin();
return 0;
}
我使用以下方法編譯它:
gcc f.c -o fc -lncurses
..當然,安裝了正確的庫。
然后我使用這個文件 test.txt 作為示例:
What is my name? Teddy Roosevolt
What is my name? Teddy Roosevolt
Where am I from? USA
What is my ethnicity? Caucasian
What is my nationality? British
What is my name? Teddy Roosevolt
Where am I from? USA
What is my ethnicity? Caucasian
What is my nationality? British
What is my name? Teddy Roosevolt
Where am I from? USA
What is my ethnicity? Caucasian
What is my nationality? British
Where am I from? USA
What is my ethnicity? Caucasian
What is my nationality? British
然后我運行它:
./fc test.txt
我什么也沒得到——甚至沒有錯誤,什么都沒有。 相反,程序立即運行並立即退出。 在對無錯誤的閃存卡文件進行測試之前,我在格式錯誤的文件上對其進行了測試 - 格式錯誤的文件會引發所有正確的錯誤,這告訴我它不起作用的原因與塊無關主文件開頭的代碼檢查文件是否有效——我認為它與 ncurses 部分有關——但我不知道是什么。
謝謝你的幫助。
它真的很簡單,與 ncurses 無關:
你永遠不會倒帶你的文件!
您的valid_file
function 會讀取文件中的所有數據,而不會為main
中的循環留下任何內容。
由於在 function 之后您從未重置文件 position,因此main
中的循環永遠不會執行,因為沒有任何內容可供readline
讀取,並且您的程序結束。
您必須添加fseek(stream, 0, SEEK_SET);
在return true
之前到valid_file
的末尾。
另請注意,您永遠不會free
為您分配的readline
讀取行,您必須在每次調用后執行此操作,並將line
指針重置為 NULL 並將len
重置為 0,以使其分配新緩沖區。
否則,您最終會遇到 memory 泄漏。
如果您的文本文件很小,可能不會引起注意,但這仍然是一種不好的編程習慣!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.