C 在遍历文件时,如何通过元素索引循环而不是逐字符进行迭代
我的问题是,我如何让代码通过它的索引位置,同时也得到它的长度,而不是通过逐字符进行。类似下面的内容(不起作用)C 在遍历文件时,如何通过元素索引循环而不是逐字符进行迭代,c,C,我的问题是,我如何让代码通过它的索引位置,同时也得到它的长度,而不是通过逐字符进行。类似下面的内容(不起作用) #包括 int main(int argc,字符**argv){ INTC; 文件*文件; file=fopen(argv[1],“r”); int i=0; 如果(文件){ 而(我0) { 对于(尺寸i=0;i
#包括
int main(int argc,字符**argv){
INTC;
文件*文件;
file=fopen(argv[1],“r”);
int i=0;
如果(文件){
而(我
像这样的事情应该会让你开始
#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++;
}
}
}
另一种方法是使用
fgets
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);
...
int main(int argc, char **argv)
{
char buffer[BUFSIZ];
FILE *file;
file = fopen(argv[1], "r");
if (file)
{
// Read BUFSIZ-1 number of characters at a time.
while ( fgets(buffer, BUFSIZ, file) != NULL )
{
for ( size_t i = 0; buffer[i] != '\0'; ++i )
{
char c = buffer[i];
if (c != 'a')
{
putchar(c);
}
}
}
}
}
如果文件包含二进制数据,则可以使用fread
而不是fgets
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);
...
int main(int argc, char **argv)
{
char buffer[BUFSIZ];
FILE *file;
file = fopen(argv[1], "r");
if (file)
{
// Read BUFSIZ-1 number of characters at a time.
while ( fgets(buffer, BUFSIZ, file) != NULL )
{
for ( size_t i = 0; buffer[i] != '\0'; ++i )
{
char c = buffer[i];
if (c != 'a')
{
putchar(c);
}
}
}
}
}
int main(int argc,char**argv)
{
字符缓冲区[BUFSIZ];
文件*文件;
file=fopen(argv[1],“r”);
如果(文件)
{
//一次读取BUFSIZ的字符数。
尺寸n=0;
而((n=fread(buffer,1,BUFSIZ,file))>0)
{
对于(尺寸i=0;i
除了内存映射文件之外?我试图给出一个示例,说明我希望它如何通过索引进行索引。显然,要做到这一点,您必须先将文件读入缓冲区。确定文件长度(各种技术),然后使用一个如此大的缓冲区malloc()读取整个文件,就可以开始了。如果它是一个长寿命的应用程序,那么在完成时当然还需要释放()缓冲区。或者正如@IgnacioVazquez Abrams提到的,将文件映射到内存是另一种方法。为什么要这样做?您可以使用fread
将文件逐块读取到缓冲区中(缓冲区的长度由您选择),并为缓冲区编制索引。
int main(int argc, char **argv)
{
char buffer[BUFSIZ];
FILE *file;
file = fopen(argv[1], "r");
if (file)
{
// Read BUFSIZ number of characters at a time.
size_t n = 0;
while ( (n = fread(buffer, 1, BUFSIZ, file)) > 0 )
{
for ( size_t i = 0; i < n; ++i )
{
char c = buffer[i];
if (c != 'a')
{
putchar(c);
}
}
}
}
}