帮我写一段c代码实现判断某个文件是否存在代码需要能跨平台并给出CMakeList
.txt文件。
以下是实现该功能的C代码:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif
bool file_exists(const char* filename) {
FILE* file = fopen(filename, "r");
if (file != NULL) {
fclose(file);
return true;
}
return false;
}
int main() {
const char* filename = "example.txt";
if (file_exists(filename)) {
printf("File %s exists.\n", filename);
} else {
printf("File %s does not exist.\n", filename);
}
return 0;
}
该代码使用了标准C库中的fopen函数来尝试打开文件,如果文件存在,则返回非NULL值,表明文件存在;否则返回NULL,表明文件不存在。
为了实现跨平台,该代码使用了条件编译,通过判断宏定义_WIN32是否被定义来区分Windows和其他平台。对于Windows平台,我们使用了Windows API中的函数来判断文件是否存在;对于其他平台,我们使用了标准C库中的函数。
以下是该代码的CMakeLists.txt文件:
cmake_minimum_required(VERSION 3.5)
project(file_exists)
set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)
add_executable(file_exists file_exists.c)
该CMakeLists.txt文件指定了编译器的标准为C11,并且将编译器的标准设置为必须满足。然后,它创建一个名为file_exists的可执行文件,该文件只包含了一个源文件file_exists.c。
原文地址: http://www.cveoy.top/t/topic/GCy 著作权归作者所有。请勿转载和采集!