将文本文件的全部内容复制到字符数组变量中

时间:2015-10-27 00:39:57

标签: c file

我必须将名为Bond.in的文本文档的内容放入字符数组变量中。我已经尝试了几种方法将Bond.in的内容保存到一个字符数组中,但下面的那个是唯一可以工作的方法。但是,每当我尝试使用my_getline函数(我们在类中编写的一个我们必须使用的函数)打印变量数组的内容时,它就会进入无限循环。我无法弄清楚这是因为调用my_getline的for循环还是Bond.in的内容没有正确复制到text []。任何指导将不胜感激。另外,如果我遗漏任何有用的东西,请告诉我。

/*   Include the standard input/output and string libraries             */
#include <stdio.h>
#include <string.h>

/*   Define the maximum lines allowed in an input text and NEWLINE for getline funct.   */
#define MAXPATTERN 15
#define MAXWORDS 150
#define NEWLINE '\n'

/*   function prototypes                                */
void my_getline(char text[]);
int find_string(char text[], char pattern[], int length_text, int length_pattern);

int main()
{
   FILE *fp;
   char text[MAXWORDS];
   int i = 0, j;
   char fileName[15] = "Bond.in";
   char pattern[MAXPATTERN], c;
   int length_text, length_pattern, count;

   fp = fopen(fileName, "r");
   if (fp == NULL)
   {
      printf("fopen failed.\n");
      return(-1);
   }

   while(feof(fp))
      text[i++] = fgetc(fp);
   text[i] = '\0';

   printf("%s has been copied.", fileName);

   for (j = 0; text[j] != EOF; j++)
   {
      my_getline(text);
      printf("%d  %s \n", j, text);
   }

   printf("Enter the pattern you would like to search for: ");
   scanf("%s", pattern);
   printf("\nYou have chosen to search for: %s\n", pattern);

   //printf("%s appears %d times in %s.\n", pattern, find_string(text, pattern, length_text, length_pattern), fileName);
   fclose(fp);

   return(0);
}

void my_getline(char text[])
{
   int i = 0;
   while ((text[i] = getchar()) != NEWLINE)
      ++i;
   text[i] = '\0';
}

Bond.in

    Secret agent Bond had been warned not to tangle with Goldfinger.
But the super-criminal's latest obsession was too strong, too dangerous.
He had to be stopped.
    Goldfinger was determined to take possession of half the supply of
mined gold in the world--to rob Fort Knox!
    For this incredible venture he had enlisted the aid of the top
criminals in the U.S.A., including a bevy of beautiful thieves from the
Bronx.  And it would take all of Bond's unique talents to make it fail--
as fail it must.

2 个答案:

答案 0 :(得分:1)

你永远不会将ATNO放入EOF,所以你的循环永远不会停止也就不足为奇了。你 在最后放了一个text,所以你的打印循环应该正在寻找。

答案 1 :(得分:0)

此:

   fp = fopen(fileName, "r");
   if (fp == NULL)
   {
      printf("fopen failed.\n");
      return(-1);
   }

   while(feof(fp))
      text[i++] = fgetc(fp);
   text[i] = '\0';

读取零字节,因为feof(fp)在文件打开后立即为假。

这个

void my_getline(char text[])
{
   int i = 0;
   while ((text[i] = getchar()) != NEWLINE)
      ++i;
   text[i] = '\0';
}

text中的所有内容替换为从stdin读取的数据,直到读入换行符,从而覆盖您已经读过的所有内容。

这将读取文件的内容并NUL终止它(假设文件内容,POSIX环境中没有NUL字符):

int fd = open( filename, O_RDONLY );
struct stat sb;
fstat( fd, &sb );
char *contents = calloc( 1, sb.st_size + 1 );
read( fd, contents, sb.st_size );
close( fd );

错误检查留作练习。