我正在尝试打开一个只有在目录中创建后才知道的文件,但是 FILE *infile (等等,等等..)函数在这种情况下不起作用,因为“infile”以前没有已被取消。我不知道如何在循环之前声明它,以便它获取当时正在迭代的当前文件。
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <sys/inotify.h>
#include <openssl/sha.h>
int main (int argc, char *argv[])
{
int result;
int fd;
int wd;
unsigned char c[SHA512_DIGEST_LENGTH];
int i;
//FILE *inFile = fopen (filename, "rb"); //I'm aware this would usually
//be declared here
SHA512_CTX mdContext;
int bytes;
unsigned char data[1024];
const int event_size = sizeof(struct inotify_event);
const int buf_len = 1024 * (event_size + FILENAME_MAX);
fd = inotify_init();
if (fd < 0) {
perror("inotify_init");
}
wd = inotify_add_watch(fd, "/home/joe/Documents", IN_CREATE);
while (1) {
char buff[buf_len];
char target[FILENAME_MAX];
int no_of_events, count = 0;
no_of_events = read (fd, buff, buf_len);
while (count < no_of_events) {
struct inotify_event *event = (struct inotify_event *)&buff[count];
if (event->len) {
if (event->mask & IN_CREATE)
if(!(event->mask & IN_ISDIR)) {
printf("The file %s has been created\n", event->name);
//FILE *infile = fopen (filename, "rb"); //issue arises here
//when not commented
SHA512_Init (&mdContext);
while ((bytes = fread (data, 1, 1024, filename)) != 0)
SHA512_Update (&mdContext, data, bytes);
SHA512_Final (c,&mdContext);
for(i = 0; i < SHA512_DIGEST_LENGTH; i++) printf("%02x", c[i]);
printf (" %s\n", event->name);
fclose (filename);
return 0;
fflush(stdout);
}
}
count += event_size + event->len;
}
}
return 0;
}
我正在尝试解决这个问题,因此有评论和未声明的“文件名”。
最佳答案
您要打开的文件的名称存储在event->name
中。这就是您想要传递给 fopen
的内容。另外,您希望将 infile
传递给 fread
和 fclose
。
FILE *infile = fopen (event->name, "rb"); // event->name is the filename
SHA512_Init (&mdContext);
while ((bytes = fread (data, 1, 1024, infile )) != 0) // read from infile
SHA512_Update (&mdContext, data, bytes);
SHA512_Final (c,&mdContext);
for(i = 0; i < SHA512_DIGEST_LENGTH; i++) printf("%02x", c[i]);
printf (" %s\n", event->name);
fclose (infile); // close infile
关于c - 如何在 while 循环中打开依赖于尚未声明的信息的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55025069/