gpt4 book ai didi

c - 如何使用读取功能,大小未知

转载 作者:行者123 更新时间:2023-11-30 20:03:35 25 4
gpt4 key购买 nike

我创建了一个函数来打开文件并读取其中的单个字符。

int getBlocks(char *file){

char c;
int line = 0;
int pos = 0;
int blocks;

FILE *inptr = fopen(file, "rt");

// Count the amount of blocks/tetriminos
while((c=fgetc(inptr))!=EOF){

if(c == '.' || c == '#'){
pos++;
if(pos == 4){
pos = 0;
line++;
}
}
}

blocks = (line/4);
fclose(inptr);

return blocks;
}

现在我必须重写它,因为我唯一可以使用的函数是 exitopenclose写入读取malloc释放

我认为我基本上可以使用 int inptr = open(file, O_RDONLY); 而不是我的 fopen 行,并且只需 close(inptr); 而不是我的 fclose 函数。

我现在唯一的问题是fgetc。我很确定我可以在这里使用 read ,但根据它的定义 ssize_t read(int fildes, void *buf, size_t nbytes); 我需要告诉一个提前固定字节数,但在我的情况下文件大小总是不同。

你知道我如何在这里重写fgetc吗?

最佳答案

非常相似,略有变化

char chr;
int fd = open(file, O_RDONLY);
if (fd == -1)
reutnr -1; // Or some error integer
while (read(fd, &chr, 1) == 1) {
/* the rest of your code */
}
close(fd);

请注意,一个重要的变化是 chr 的类型是 char 而不是 int

您只需检查 read() 是否返回了合适的值,而不是检查 EOF,理想情况下您应该将其存储在某处并检查它是否为 0 code> 位于循环末尾,表示已到达文件末尾,否则会发生错误。

关于c - 如何使用读取功能,大小未知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49059593/

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