gpt4 book ai didi

c - 如何使用chdir系统功能

转载 作者:太空宇宙 更新时间:2023-11-04 06:22:17 24 4
gpt4 key购买 nike

我正在尝试使用 chdir 来更改我的进程的工作目录。假设我的当前目录中有一个 apple 目录。为什么我在提示中输入apple 返回的结果是-1?是不是因为我输入apple的时候,'\n'字符也放在了字符串的末尾?另外,如果我只能用一个变量来存储它,那么改变目录有什么意义?

#include<stdio.h>
#include<string.h>
#include<errno.h>
#include<unistd.h>

int main(void){
char path[256];
fgets(path, 256, stdin);
printf("%s", path);
int result = chdir(path);
if(result != 0){
printf("%d\n", result);
}
}

最佳答案

fgets() 在结果后加上 可能(如果没有收到EOF)读取一个新行(\n 在 IXish 系统上)并将其传递给 chdir() 会使后者窒息,因为要更改为大多数 likley 的目录名称不带有尾随换行符。

来自 man fgets() (我的斜体):

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer.


关于调试的注意事项:如果您将要打印的“字符串”(如 fgets() 读取的那样)放在这样的引号中

printf("'%s'", path);

您可能已经注意到尾随 \n

关于c - 如何使用chdir系统功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32679634/

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