gpt4 book ai didi

c - 为什么我的 C 程序的行为会根据其执行目录的不同而有所不同?

转载 作者:太空宇宙 更新时间:2023-11-04 01:33:00 29 4
gpt4 key购买 nike

这让我发疯。我编写了一个接受用户输入文件名的程序。它在我的 ~/documents/cs 目录中按预期运行,但在我的 ~/documents/cs/assign5 目录中失败。这对我来说完全没有意义。为什么程序的行为会根据其所在的目录而有所不同?

在父目录中执行的良好输出:

./a.out - file2
Enter the filename: file1
FILE1
FILE2

assign5 目录的错误输出:

./a.out - file2
Enter the filename: file1
file1
n: No such file or directory

我什至尝试将 assign5 目录重命名为其他名称,但效果很好。

该程序基本上采用两个命令行参数。如果存在“-”命令行参数,它会要求输入文件名。然后它将两个文件的内容打印到标准输出。这是程序失败的地方(仅在 assign5 目录中...)。似乎当程序在 assign5 目录中运行时,userInput 变量存储的是值“n”而不是“file1”。为什么!?

if(strcmp(argv[1], "-") == 0) // use standard-in for input file 1
{
printf("Enter the filename: ");
fflush(NULL);
read(STDIN_FILENO, userInput, sizeof(userInput));
userInput[strlen(userInput)-1] = '\0';
if((input_file1 = open(userInput, O_RDONLY)) < 0)
{
perror(userInput);
exit(1);
}

更新:

我在名为“assign5”的目录中的远程 Linux 服务器上运行了完全相同的代码,并按预期编译和执行。那么,我的电脑有什么问题吗?

最佳答案

不要使用read。除非您知道自己在做什么,否则它会搞砸您所有的 I/O。

read 返回的输入上的

strlen 充其量会导致 SIGSEGV,最坏情况下会导致未定义的行为,如您所观察到的那样。使用 scanf

scanf("%s", userInput); // will add a null terminator itself

如果您真的必须使用read,那么您需要手动完成scanf 为您完成的工作:

// reserve space for the null terminator
int bytes_read = read(STDIN_FILENO, userInput, sizeof(userInput) - 1);
if (bytes_read < 0) {
perror("read");
abort();
}

// add the null terminator
userInput[bytes_read] = '\0';

// you will most likely have a newline in the input
while (isspace(userInput[bytes_read - 1]))
userInput[--bytes_read] = '\0';

char * filename = userInput;

// you may have preceding spaces
while (isspace(*filename))
filename++;

另请注意,由于未定义的原因,read 可能会在读取整个输入之前返回,在这种情况下,理想情况下您应该再次调用它,直到它返回 0。scanf 可以这一切都是为了你。

关于c - 为什么我的 C 程序的行为会根据其执行目录的不同而有所不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19729487/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com