C语言 如何从一个文件中读取一段含\n的字符串

如题所述

使用fread函数读取指定长度的字符串,即使包含\n也会被读取,可以首先使用fseek定位到文件结尾,然后ftell函数返回的值就是文件的大小,这样就可以用循环多次读取文件,直到读取所有内容

FILE *file = NULL;
char szFile[1025] = {0};
int nHadRead = 0;
file = fopen( "file.txt", "r+");
if ( file == NULL )
return;

fseek( file, 0, SEEK_END ); //定位到文件尾
int nLen = ftell( file ); //获取当前位置,即文件长度
fseek( file 0, SEEK_SET ); //重新定位到文件开头,准备开始读
while ( nHadRead < nLen )
{
int nRead = nLen - nHadRead >1024 ? 1024 : nLen - nHadRead; //如果剩余小于1024字节,则读剩余字节,否则每次读取1024字节。
int nTmp = fread( szFile, 1, nRead , file );
nHadRead += nTmp;

printf( "%s", szFile );

memset( szFile, 0x0, sizeof(szFile) );
}
fclose(file);

大致过程就是这样,纯手打,没有调试过,可能有错
温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-09-26

1、可以使用fgets()函数从文件中 读一行字符串,存入char 型数组,自动含\n。
2、下面例程读一行输出1行。

#include <stdio.h>
int main()
{
   FILE * pFile;
   char mystring [1000];
   pFile = fopen ("myfile.txt" , "r");
   if (pFile == NULL) perror ("Error opening file");
   else {
     if ( fgets (mystring , 1000 , pFile) != NULL )//读取一行字符串
       puts (mystring);//输出该字符串
     fclose (pFile);
   }
   return 0;
}

第2个回答  2013-11-10
fgets() 读一行字符串,存入char 型数组,自动含\n。
下面程序读一行输出1行。
#include <stdio.h>
int main()
{
FILE * pFile;
char mystring [1000];

pFile = fopen ("myfile.txt" , "r");
if (pFile == NULL) perror ("Error opening file");
else {
if ( fgets (mystring , 1000 , pFile) != NULL )
puts (mystring);
fclose (pFile);
}
return 0;
}
第3个回答  2013-11-10
如果是MFC的话,对新手推荐使用CStdioFile这个类.
CStdioFile pfile;
CString tmp;
pfile.Open("temp.txt",CStdioFile::modeReadWrite);//打开一个文本文件,如果你没有写全文件的路径,则默认是在exe程序下的文件。
pfile.ReadString(tmp);//读取文本的一整行字串,同时指针移动到下一行的起始位置。
//其它的操作

//
pfile.Close();//完成后关闭
第4个回答  2013-11-10
函数fgets