0
我有下面的代碼(不是我的)試圖讓它工作出好奇。 從這裏C low-level standard-in to accept filename then printing file contents to stdout無法獲取文件使用讀取/ fgets /寫入標準輸出在C
int checkfile(void)
{
char buffer[4096];
char userInput[100];
int input_file1;
int n;
/* Check file existence. */
printf("Enter the filename: \n");
fflush(NULL);
if (!fgets(userInput,sizeof(userInput),stdin))
{
perror("fgets");
exit(EXIT_FAILURE); };
if((input_file1 = open(userInput, O_RDONLY)) < 0)
{
perror(userInput);
exit(1);
}
while((n = read(input_file1, buffer, sizeof(buffer))) > 0)
{
if((write(STDOUT_FILENO, buffer, n)) < 0)
{
perror("failed to display file to output");
close(input_file1);
exit(1);
}
}
}
每當我運行的代碼,並嘗試打開一個名爲「success.txt」我得到一個分段錯誤
"RUN FINISHED; Segmentation fault; core dumped; real time: 3s; user: 0ms; system: 0ms"
我也從我的主要代碼調用此as
checkfile();
如果這有什麼區別。
有人能指出我失蹤的原因,因爲此刻我看不到它。我有一種感覺,我的一些變量設置不正確......但不確定謝謝。
好的真棒,那解決了我的seg故障。現在它已經成功完成,但仍然不顯示我的文件的內容,只是進入我的主要功能中的下一代代碼?似乎它不寫入標準輸出 – LewisFletch 2015-04-05 06:19:47
是的,沒有得到編譯器錯誤。所以更新後的那一段代碼我現在得到「沒有這樣的文件或目錄」,即使該文件位於編譯文件夾的根目錄..?任何想法,爲什麼這可能是?對不起仍然包裹我的頭文件處理...謝謝@ R Sahu – LewisFletch 2015-04-05 06:30:33
@LewisFletch,看到第二次更新。 – 2015-04-05 06:33:36