strcpy(cmd, "cat /tmp/returnValue"); do { if (counter > 10) return HUAYI_FALSE; else if (counter) sleep(1); if (resultbuf) free(resultbuf); getCmdResult(cmd, &resultbuf, &bufsize); counter++; } while (!strlen(resultbuf)); 这段检查文件是否存在并且有内容的值我还想优化
时间: 2024-04-09 20:33:08 浏览: 76
如果你想优化这段代码来检查文件是否存在并且有内容,可以考虑使用 `access` 函数来检查文件是否存在,并结合 `stat` 函数来判断文件大小是否为0。以下是一种可能的优化方案:
```c
#include <unistd.h>
#include <sys/stat.h>
HUAYI_BOOL checkFileExistsAndNotEmpty(const char* filename) {
// 检查文件是否存在
if (access(filename, F_OK) == -1) {
return HUAYI_FALSE;
}
// 检查文件大小是否为0
struct stat fileStat;
if (stat(filename, &fileStat) == -1) {
return HUAYI_FALSE;
}
if (fileStat.st_size == 0) {
return HUAYI_FALSE;
}
return HUAYI_TRUE;
}
...
strcpy(cmd, "cat /tmp/returnValue");
do {
if (counter > 10) {
return HUAYI_FALSE;
} else if (counter) {
sleep(1);
}
if (resultbuf) {
free(resultbuf);
}
getCmdResult(cmd, &resultbuf, &bufsize);
counter++;
} while (!checkFileExistsAndNotEmpty("/tmp/returnValue"));
```
在上面的代码中,`checkFileExistsAndNotEmpty` 函数会先使用 `access` 函数检查文件是否存在,然后使用 `stat` 函数获取文件大小,并判断是否为0。这样可以更准确地检查文件是否存在并且有内容。
阅读全文
相关推荐















