有没有一种方法可以将变量作为参数传递给C中的int open()函数?
我是C语言的初学者,我正在做一个项目,我需要打开一个目录作为参数,访问其中的每个文件,检查其中的一些内容,编辑它们,并将结果收集到一个文本文件中。但是,当我试图通过while循环访问每个文件时,open()函数并没有按预期工作。以下是相关代码:有没有一种方法可以将变量作为参数传递给C中的int open()函数?,c,C,我是C语言的初学者,我正在做一个项目,我需要打开一个目录作为参数,访问其中的每个文件,检查其中的一些内容,编辑它们,并将结果收集到一个文本文件中。但是,当我试图通过while循环访问每个文件时,open()函数并没有按预期工作。以下是相关代码: DIR *folder; struct dirent *entry; folder = opendir(argv[1]); if(folder == NULL){ perror("Unable
DIR *folder;
struct dirent *entry;
folder = opendir(argv[1]);
if(folder == NULL){
perror("Unable to read directory or directory doesn't exist");
exit(1);
}
if( (wfd=open("output.txt", O_WRONLY | O_CREAT, 0600)) == -1 ){
perror("open"); /*Creating the text file */
exit(EXIT_FAILURE);
}
close(wfd);
while( (entry=readdir(folder)) ){
fd=open(entry->d_name, O_RDONLY);
if(fd == -1 ){
perror("open1");
exit(EXIT_FAILURE);
}
/*opening and reading the file*/
bytes=read(fd,buf,sizeof(buf));
printf("%d bytes were read \n", bytes);
close(fd);
buf[bytes]='\0';
.
. /*Rest of the code where I check edit and write the results in the outfile.txt*/
.
}
所以你可以理解
fd=open(entry->d_name, O_RDONLY);
部件失败,随后出现错误消息“open1:没有这样的文件或目录”。我知道open()函数需要一个const*char,比如文件名的确切名称“filename.txt”,但是当我假设不知道我正在处理的目录的内容时,我该怎么做呢?我尝试将entry->d_name变量转换为char变量,如下所示:
char entryName[255];
strncpy(entryName, entry->d_name, 254);
entryName[254]='\0';
然后
fd=open(entryName, O_RDONLY);
但我也犯了同样的错误。是否有我缺少的东西或应该以另一种方式实现?除非您已
chdir()
ed进入目标目录,否则不能只执行fd=open(entry->d_name,O_RDONLY)代码>希望在那里打开条目->d_name
。你可能想用fd=openat(dirfd(folder),entry->d_name,O_RDONLY)
来代替它。我认为它失败了,因为entry->d_name
只包含文件名,而不是文件的路径,而且因为你当前的工作目录不是文件夹,你会得到“没有这样的文件或目录”.一般来说,将变量传递给open
或任何其他需要字符串的函数都没有问题constchar*
只是意味着open
承诺不修改传递给它的字符串。看起来你认为a是必需的,但事实并非如此。