C中的文件I / O从文本文件中读取字符串

问题描述 投票:0回答:1

我在将单个文本文件的所有内容读取为字符串时遇到麻烦。每当有换行符时,它都不会保留先前的字符串。

例如,如果文件包含:

this is stack overflow
and it is cool

读取文件后字符串仅有的东西是“很酷”

这里是代码:

FILE *inputFilePtr;
        inputFilePtr = fopen(inputFileName, "r");
        char plainText[10000];

        // if the file does not exist
        if (inputFilePtr == NULL)
        {
            printf("Could not open file %s", inputFileName);
        }

        // read the text from the file into a string
        while (fgets(plainText, "%s", inputFilePtr))
        {
            fscanf(inputFilePtr, "%s", plainText);
        }
        printf("%s\n", plainText);
        fclose(inputFilePtr);

非常感谢您的帮助!

c string file-io text-files c-strings
1个回答
0
投票

如果要显示所有文件内容,请尝试:

    FILE *inputFilePtr;
    inputFilePtr = fopen(inputFileName, "r");
    char plainText[10000];

    // if the file does not exist
    if (inputFilePtr == NULL)
    {
        printf("Could not open file %s", inputFileName);
    }

    // read the text from the file into a string
    while (!feof(inputFilePtr)) //while we are not at the end of the file
    {
       fgets(plainText, "%s", inputFilePtr);
       printf("%s\n", plainText);
    }
     fclose(inputFilePtr);

或者如果您想以一个字符串显示所有文件内容,请使用:

#include <string.h>
 int main()
 {
   FILE *inputFilePtr;
    inputFilePtr = fopen(inputFileName, "r");
    char plainText[10000];
    char buffer[10000];


  // if the file does not exist
    if (inputFilePtr == NULL)
    {
        printf("Could not open file %s", inputFileName);
    }

    // read the text from the file into a string
    while (!feof(inputFilePtr))
    {
      fgets(buffer, "%s", inputFilePtr);
      strcat(plainText,buffer);
    }
     printf("%s\n", plainText);
     fclose(inputFilePtr);

 }
© www.soinside.com 2019 - 2024. All rights reserved.