【问题标题】:How to write text from file to a string in C如何将文件中的文本写入C中的字符串
【发布时间】:2014-12-11 18:27:56
【问题描述】:

如果要求用户写文件名,我想写代码。然后我想分析一个符号的文件内容,比如说'e'

我的问题是我不知道如何以正确的方式开始分析文件以便检查内容。

int main() {
    char c[1000], file_name[1000];
    int i;
    int s = 0;
    FILE *fp;

    printf("Enter the name of file you wish to see\n");
    gets(file_name);

    if ((fp = fopen(file_name, "r")) == NULL){
        printf("Error! opening file");
        exit(1);

    }

    if (fp) {
        while (fscanf(fp, "%s", c) != EOF) {
            printf("%s", c);
        }

        fclose(fp);

        for (i = 0; c[i] != '\0'; ++i) {
            puts(c);
            if (c[i] == 'e') {
                ++s;
            }
        }

        printf("\nWhite spaces: %d", s);
        _getche();
        return 0;
    }
}

【问题讨论】:

  • “写”是指“读”吗?
  • 将文件的内容保存为字符串,这样我就可以运行 c[i]
  • 您需要一个 char* 来存储所有内容。然后,在你的 while 循环中,执行 strcat(myFullString, c); 这会将新内容附加到“myFullString”数组中,然后你就可以在你的 for 循环中使用 is 看看这个例子:programmingsimplified.com/c-program-concatenate-strings
  • 如果我理解正确,我必须添加一个字符指针吗?非常抱歉,我对 C 和编程非常陌生,但我对它充满热情。
  • 您在寻找fread() 吗? cplusplus.com/reference/cstdio/fread 试试fread(c,sizeof(char),1000,fp); 请记住,在这种情况下,c 是一个字符数组,而不是字符串。如果您希望 c 保留字符串:fread(c,sizeof(char),999,fp);c[999]='\0';

标签: c arrays string text


【解决方案1】:
char line[512]; /*To fetch a line from file maximum of 512 char*/
rewind(fp);
memset(line,0,sizeof(line)); /*Initialize to NULL*/
while ( fgets(line, 512, fp ) && fp !=EOF)
{

/*Suppose u want to analyze string "WELL_DONE" in this fetched line.*/

  if(strstr(line,"WELL_DONE")!=NULL)
  {
    printf("\nFOUND KEYWOD!!\n");
  }
  memset(line,0,sizeof(line)); /*Initialize to null to fetch again*/
}

【讨论】:

    【解决方案2】:

    如果它只是您要查找的符号或 char,您可以简单地使用 getc() :

    int c;
    ....
    if (fp) {
        while ((c = getc(fp)) != EOF) {
            if (c == 'e') {
                // Do what you need
            }
        }
    

    或者,或者,如果它是您要查找的单词, fscanf() 将完成这项工作:

    int c;
    char symb[100];
    char symbToFind[] = "watever";  // This is the word you're looking for
    ....
    while ((c = fscanf(fp, %s, symb)) != EOF) {
        if (strcmp(symb, symbToFind) == 0) {  // strcmp will compare every word in the file
            // do whatever                    // to symbToFind
        }
    }
    

    这些替代方法将允许您搜索文件中的每个字符或字符串,而无需将它们保存为数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-04
      • 2011-09-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多