在 C 中将变量传递给 chdir() (Linux)
我的 C 程序中的 chdir() 遇到问题 - 仅当在 Linux 上运行时(在 Mac 上工作正常)。我已经剥离了我的代码。
像这样的东西工作得很好:
chdir("/Documents");
但是当我尝试将它作为变量传递时,它不想工作。
char *home_directory;
home_directory = malloc(80);
chdir(home_directory);
主目录是从我的代码中其他位置的文件中读取的,如果需要,我可以发布我是如何做到这一点的。
谢谢。
I'm having a problem with chdir() in my C program - only when running on Linux (works fine on Mac). I've stripped down my code.
Something like this works fine:
chdir("/Documents");
but when I try to pass it as a variable it doesn't want to work.
char *home_directory;
home_directory = malloc(80);
chdir(home_directory);
Home directory is read from a file elsewhere in my code, I can post how I've done that if needed.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于您正在从文件中读取
home_directory
,因此您是否忘记在将其用作chdir
的参数之前删除尾随换行符和任何其他虚假字符?Since you are reading
home_directory
from a file, have you forgotten to remove a trailing newline and any other spurious characters before you use it as a parameter tochdir
?尝试进行一些错误检查,如下所示;
..然后使用
man chdir
就可以查找错误代码的含义。Try doing some error checking, like this;
.. and then with a
man chdir
yo can look up the meaning of the error code.由于
chdir
是Linux上的系统调用,因此您可以简单地使用strace
程序来查看您的程序到底做了什么。这并不能让您免于在代码中预先处理错误;明显地。它只是帮助您遵循程序所采取的操作。Since
chdir
is a system call on Linux, you can simply use thestrace
program to see what your program really does. That doesn't free you from handling errors preoperly in your code; obviously. It just helps you to follow the actions that your program takes.