【问题标题】:Basic C Questions. fprintf and fgets failures基本 C 问题。 fprintf 和 fgets 失败
【发布时间】:2015-02-23 06:39:44
【问题描述】:

我有一些基本的 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 returned NULL")。请注意,应用程序仍然给我“未输入源文件”的错误。我的目标是 stdout 还是 stderr 都没关系。

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

编辑:我刚刚注意到 if 语句(fgets one)上缺少括号。让我看看解决了什么问题。

【问题讨论】:

  • 提示:当你调用GetLine("Please enter a source file name: \n", sourceFile, 100);时,sourceFile有什么值? (指针本身)
  • 而且,如果您的问题得到了解答,请不要修复问题中的代码,因为您似乎从未遇到过这个问题。如果您已接受答案,并且您的代码有其他不相关的问题,请发布另一个问题。

标签: c


【解决方案1】:
if (fgets (buff, sz, stdin) == NULL)
    fprintf(stderr, "fgets returned NULL");
    return NO_INPUT;

无论fgets() 返回什么,这里总是执行return NO_INPUT;。使用{} 将这两个语句括起来。

【讨论】:

  • 哈哈我也看到了。谢谢你。这完美地解释了这两个错误
  • 这就是我在 Python 中编程所得到的。这看起来很正常
  • 好的,现在又出现了一个错误。我们第二次调用 GetLine 时,fgets 仍然失败并出现总线错误。它不返回 NULL。它只是使程序崩溃。想法?
【解决方案2】:
if (prmpt != NULL) {
    printf("%s", prmpt);
    fflush(stdout);
}
}

您正在关闭 GetLine,但您的代码仍在继续

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-24
    相关资源
    最近更新 更多