[英]File I/O in C reading strings from a text file
I am having trouble reading all content of a single text file into a string.我无法将单个文本文件的所有内容读入字符串。 Whenever there is a line break it does not keep the previous strings.只要有换行符,它就不会保留以前的字符串。
For example if the file contained:例如,如果文件包含:
this is stack overflow
and it is cool
The only thing that the string would have after reading the file is " it is cool"读取文件后字符串的唯一内容是“它很酷”
here is the code:这是代码:
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);
Any Help is greatly appreciated!任何帮助是极大的赞赏!
If you want to display all file contents try:如果要显示所有文件内容,请尝试:
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);
Or if you want to display all file contents in one string use:或者,如果您想在一个字符串中显示所有文件内容,请使用:
#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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.