【发布时间】: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 帖子提供。这是我的问题。
无论我做什么,我都无法让调试打印语句正常工作。基本的 printf 经常会失败。之后立即调用 fflush(stdout) 没有帮助,setbuf(stdout, NULL) 也没有帮助。现在我正在尝试 fprintf(stderr),也无济于事。不断失败的 LOC(不管我尝试哪种方法)是 fprintf(stderr, "fgets returned NULL")。请注意,应用程序仍然给我“未输入源文件”的错误。我的目标是 stdout 还是 stderr 都没关系。
fgets 每次都返回 NULL。我不知道为什么。不,我提供的输入不大。
编辑:我刚刚注意到 if 语句(fgets one)上缺少括号。让我看看解决了什么问题。
【问题讨论】:
-
提示:当你调用
GetLine("Please enter a source file name: \n", sourceFile, 100);时,sourceFile有什么值? (指针本身) -
而且,如果您的问题得到了解答,请不要修复问题中的代码,因为您似乎从未遇到过这个问题。如果您已接受答案,并且您的代码有其他不相关的问题,请发布另一个问题。
标签: c