簡體   English   中英

C語言從文件讀取到字符數組

[英]C language reading from file to char array

我正在嘗試逐個字符地從文件中讀取到一個數組中。 這是我的代碼:

#include <stdio.h>
#include <stdlib.h>

int main()
{
   FILE * fp;
   char abc[255];
   int i = 0;

   fp = fopen ("source.c", "r");

   while(fgetc(fp) != EOF)
   {
       fputc(abc[i], FILE *fp );
       printf("%c", abc[i]);
       i++;
   }

   fclose(fp);

   return(0);
}

我收到一個錯誤:

main.c: In function 'main':
main.c:19:19: error: expected expression before 'FILE'
     fputc(abc[i], FILE *fp );

這個錯誤是什么意思? 出了什么問題,我該如何解決?

該錯誤是關於fputc()的不正確使用。 第二個參數是一個 但在您的情況下,您不需要調用fputc()因為您也在使用 printf()。

你還有一個問題。 您根本不存儲從文件中讀取的字符。 做類似的事情:

   int in;

   while((in=fgetc(fp)) != EOF)
   {
       in = abc[i];
       printf("%c", abc[i]);
       i++;
   }

一些一般性評論:

  • 始終對所有標准函數進行錯誤檢查。 如果fopen()失敗怎么辦?
  • 您的數組最多只能容納 256 個字符。 如果文件source.c有更多字符怎么辦?
#include <stdio.h>
#include <stdlib.h>

int main()
{
  FILE * fp;
  char abc[255];
  int i = 0;

  fp = fopen ("source.c", "r");

  // we need to make sure that we can fit
  // into buffer - that's why we check whether i < 255
  while(i<255 && (abc[i] = fgetc(fp)) != EOF)
  {
    printf("%c", abc[i]);
    i++;
  }
  // if we are way before end of the buffer
  // we should think about terminating string
  if(i<254)
    abc[i] = '\0';
  else
    // otherwise, we have to make sure that last character
    // in buffer is zero
    abc[254] = '\0';
  printf("%s", abc);

  fclose(fp);

  return(0);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM