簡體   English   中英

基本的C問題。 fprintf和fgets失敗

[英]Basic C Questions. fprintf and fgets failures

我有一些基本的C問題使我發瘋。 讓我發布我的代碼,然后我將告訴您發生了什么問題。

#include<stdio.h>
#include<fcntl.h>
#include<string.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>

static int GetLine();


int main() {
char* sourceFile;
char* destinationFile;
int error, bytesRead;
char* sourceFD;
char* destinationFD;
char buffer[100];

error = GetLine("Please enter a source file name: \n", sourceFile, 100);
if (error == 1) {
    printf("A source file was not inputted.\n");
    return 0;
}
else if (error == 2) {
    printf("Source file is too long.\n");
    return 0;
}

error = GetLine("Please enter a destination file name: \n", destinationFile, 100);
if (error == 1) {
    printf("A destination file was not inputted.\n");
    return 0;
}
else if (error == 2) {
    printf("Destination file is too long.\n");
    return 0;
}
}

#define OK       0
#define NO_INPUT 1
#define TOO_LONG 2
static int GetLine (char *prmpt, char *buff, unsigned int sz) {
int ch, extra;

// Get line with buffer overrun protection.
if (prmpt != NULL) {
    printf("%s", prmpt);
    fflush(stdout);
}
}

if (fgets (buff, sz, stdin) == NULL) {
    fprintf(stderr, "fgets returned NULL");
    return NO_INPUT;
}

printf("logging input: %s", buff);

// If it was too long, there'll be no newline. In that case, we flush
// to end of line so that excess doesn't affect the next call.
if (buff[strlen(buff)-1] != '\n') {
    extra = 0;
    while (((ch = getchar()) != '\n') && (ch != EOF))
        extra = 1;
    return (extra == 1) ? TOO_LONG : OK;
}

// Otherwise remove newline and give string back to caller.
buff[strlen(buff)-1] = '\0';
return OK;
} 

該錯誤發生在GetLine函數中,該函數主要由另一個StackOverflow帖子提供。 這是我的問題。

  1. 無論我做什么,我都無法使調試打印語句正常工作。 基本的printf經常會失敗。 之后立即調用fflush(stdout)無濟於事,setbuf(stdout,NULL)也無濟於事。 現在我正在嘗試fprintf(stderr),也無濟於事。 不斷失敗的LOC(無論我嘗試哪種方法)是fprintf(stderr,“ fgets返回NULL”)。 請注意,該應用程序仍然給我錯誤“未輸入源文件”。 我是否以stdout或stderr為目標都沒有關系。

  2. fgets每次都返回NULL。 我不知道為什么。 不,我提供的輸入不大。

編輯:我只是注意到該if語句(fgets一個)上缺少的括號。 讓我看看能解決什么問題。

if (fgets (buff, sz, stdin) == NULL)
    fprintf(stderr, "fgets returned NULL");
    return NO_INPUT;

這里return NO_INPUT; 無論fgets()返回什么,總是執行。 使用{}將兩個語句括起來。

if (prmpt != NULL) {
    printf("%s", prmpt);
    fflush(stdout);
}
}

在這里,您正在關閉GetLine,但是您的代碼仍在繼續

暫無
暫無

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

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