gpt4 book ai didi

c - 在c中打开一个Windows文件目录以进行读/写

转载 作者:行者123 更新时间:2023-11-30 15:48:55 26 4
gpt4 key购买 nike

我正在尝试使用 c 将 Windows 目录的内容写入文件。例如,如果我有一个 jpegs 目录(即包含多个 jpeg 的目录)并希望将它们转换为 .raw 文件,我有这样的内容:

#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>

typedef uint8_t BYTE;

#define BLOCK 512*sizeof(BYTE);

int main(void)
{
FILE * fd = fopen("C:\\jpegs", "r");
if (fd == NULL) {
fprintf(stderr, "Error opening device file.\n");
return EXIT_FAILURE;
}
int block = BLOCK;
FILE * fn = fopen("new.raw", "w+");
void * buff = malloc(block);
while(feof(fd) == 0) {
fread(buff,block,1,fd);
fwrite(buff,block,1,fn);
}
free(buff);
fclose(fd);
fclose(fn);
return 0;
}

问题是我不认为 Windows 目录以 EOF 终止。有人知道如何解决这个问题吗?

最佳答案

在 Unix 系统上,虽然你可以打开一个目录进行读取,但你不能真正读取它,除非你使用 opendir(), readdir(), closedir() 系列调用。在 Unix 上你不能写入目录;即使 super 用户(root)也无法做到这一点。 (打开目录的主要原因,通常使用 open() 而不是 fopen(),是为了可以使用 chdir()然后使用 fchdir() 返回到开始的位置,或者使用各种 *at() 函数,例如 openat(),引用目录。)

在 Windows 上,您至少需要使用 "rb" 模式,但坦率地说,我不希望您能够用它做太多事情。 Windows API 中可能有与 Unix opendir() 函数类似的函数,您应该使用它们。

关于c - 在c中打开一个Windows文件目录以进行读/写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16574511/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com