如何通过元素索引循环迭代时,而不是通过文件迭代时char


#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);
            }
        }

    }
}

基本上,该程序仅将文件作为stdin接收,然后删除每个a并打印到stdout。例如

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

我的问题是,如何使代码顺利进行索引位置,也可以掌握它的长度,而不是通过char驱动。像下面的东西(它不起作用(

#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 filen");
     exit(1);
  }
  if (fread(fbuf, 1, flen, fp) != flen) // read the whole file at once
  {
     fprintf(stderr, "Error reading filen");
     exit(1);
  }
  fbuf[flen] = ''; // nul-term the buffer in case you use "str" functions on it
  fclose(fp);
  ...

另一种方法是使用 fgets

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] != ''; ++i )
         {
            char c = buffer[i];
            if (c != 'a')
            {
               putchar(c);
            }
         }
      }
   }
}

如果文件包含二进制数据,则可以使用fread而不是fgets

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);
            }
         }
      }
   }
}

最新更新