gpt4 book ai didi

c - 迭代文件时如何通过元素索引循环而不是逐个字符进行迭代

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

#include <stdio.h>

int main(int argc, char **argv) {
int c;
FILE *file;
file = fopen(argv[1], "r");
if (file) {

while ((c = getc(file)) != EOF) {
if (c != 'a') {
putchar(c);
}
}


}
}

基本上,程序只是将一个文件作为标准输入,然后删除每个 a 并打印到标准输出。例如

$ gcc -Wall removeA.c
$ echo 123a >file1
$ ./a.out file1
123

我的问题是,如何使代码通过它的索引位置来获取它的长度,而不是通过字符来获取它的长度。类似下面的东西(它不起作用)

#include <stdio.h>

int main(int argc, char **argv) {
int c;
FILE *file;
file = fopen(argv[1], "r");
int i = 0;
if (file) {

while (i < len) {
if (c[i] != 'a') {
putchar(c[i]);
}
i++;
}


}
}

最佳答案

这样的事情应该让你开始......

FILE *fp = fopen(argv[1], "r");
if (fp)
{
fseek(fp, 0, SEEK_END);
size_t flen = ftell(fp);
fseek(fp, 0, SEEK_SET);
char *fbuf = (char*)malloc(flen + 1); // +1 to add a nul-term at the end
if (!fbuf)
{
fprintf(stderr, "Out of memory trying to read file\n");
exit(1);
}
if (fread(fbuf, 1, flen, fp) != flen) // read the whole file at once
{
fprintf(stderr, "Error reading file\n");
exit(1);
}
fbuf[flen] = '\0'; // nul-term the buffer in case you use "str" functions on it
fclose(fp);
...

关于c - 迭代文件时如何通过元素索引循环而不是逐个字符进行迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49015387/

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