【发布时间】:2013-10-10 13:34:52
【问题描述】:
我在 Linux2.4、C 和使用 gcc 中有一个特殊的问题。
有一个小程序可以使用 cat & grep cmd 从文件中检索信息。
#define tmpFile "/tmp/cli_tmp_file.txt"
#define MAX_CMD 50
void getRange()
{
char cmd[MAX_CMD+1];
// remove the temp file first
snprintf(cmd, MAX_CMD, "rm -f %s", tmpFile);
system(cmd);
// create temp file
snprintf(cmd, MAX_CMD, "touch %s",tmpFile);
system(cmd);
// execute the command
snprintf(cmd, MAX_CMD, "echo \"Range:Max val 500\" > %s",tmpFile);
system(cmd);
// dump out the temp file so user could see
snprintf(cmd, MAX_CMD, "cat %s|grep \"Range\"", tmpFile);
system(cmd);
// remove the temp file
snprintf(cmd, MAX_CMD, "rm -f %s", tmpFile);
system(cmd);
}
当我执行这段代码时,我得到的输出为 cat: /tmp/cli_tmp_file.txt: 没有那个文件或目录
但是,文件是在 tmp 文件夹中创建的,其内容
# pwd
/tmp
# ls -l
-rw-r--r-- 1 root root 68 Oct 10 12:54 cli_tmp_file.txt
#more /tmp/cli_tmp_file.txt
Range:Max val 500
在手动执行相同的 cmd 时,它会显示预期的输出
# cat /tmp/cli_tmp_file.txt|grep Range
Range:Max val 500
任何帮助将不胜感激。 提前致谢。
【问题讨论】:
-
你应该检查
system的返回值,看看命令是否成功。另外,尝试在每个snprintf之后打印cmd缓冲区,看看它是否包含预期的命令。 -
删除文件,再试一次。
-
避免将
system与rm一起使用;考虑调用remove(3) 函数。要创建一个文件,只需fopen用于写入,然后fclose就在之后。不要忘记测试每个功能是否失败。 -
你不只是把它写成一个shell脚本有什么原因吗?会简单一些...