使用 Fgets 读取 cpp 文件的所有行
Read all Lines of a cpp File with Fgets
在我的简单实现中。我想读取 cpp 文件的所有行
FILE * pFile;
fopen_s(&pFile,"test.cpp","r+");
if (pFile!=NULL)
{
fputs ("fopen example", pFile);
char str [200];
while (1) {
if (fgets(str, 200, pFile) == NULL) break;
puts(str);
}
fclose (pFile);
}
我的 text.cpp 包含这个:
Testline1
Testline2
Testline3
Testline4
作为输出,我得到了不可读的字符:
ÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ
我的代码有什么问题?
我的想法是专门搜索一行代码,稍后再编辑
当文件打开更新时,你想在写入后读取2你需要调用fflush1。所以在这里写入文件后调用它:
fputs ("fopen example", pFile);
1(引自ISO/IEC 9899:201x 7.21.5.3 fopen函数7)
但是,输出不得直接跟在没有
对 fflush 函数或文件定位函数(fseek,
fsetpos,或倒带)
2输出正在写入文件,输入正在读取文件。
这段代码应该可以实现您的目标:
#include <stdio.h>
#define MAX_LINE 1024
int main(int argc, char *argv[])
{
FILE *pFile;
char buf[MAX_LINE];
fopen_s(&pFile, "test.cpp", "r");
if (pFile == NULL)
{
printf("Could not open file for reading.\n");
return 1;
}
while (fgets(buf, MAX_LINE, pFile))
{
printf("%s", buf);
}
fclose(pFile);
}
在我的简单实现中。我想读取 cpp 文件的所有行
FILE * pFile;
fopen_s(&pFile,"test.cpp","r+");
if (pFile!=NULL)
{
fputs ("fopen example", pFile);
char str [200];
while (1) {
if (fgets(str, 200, pFile) == NULL) break;
puts(str);
}
fclose (pFile);
}
我的 text.cpp 包含这个:
Testline1
Testline2
Testline3
Testline4
作为输出,我得到了不可读的字符:
ÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ
我的代码有什么问题?
我的想法是专门搜索一行代码,稍后再编辑
当文件打开更新时,你想在写入后读取2你需要调用fflush1。所以在这里写入文件后调用它:
fputs ("fopen example", pFile);
1(引自ISO/IEC 9899:201x 7.21.5.3 fopen函数7)
但是,输出不得直接跟在没有
对 fflush 函数或文件定位函数(fseek,
fsetpos,或倒带)
2输出正在写入文件,输入正在读取文件。
这段代码应该可以实现您的目标:
#include <stdio.h>
#define MAX_LINE 1024
int main(int argc, char *argv[])
{
FILE *pFile;
char buf[MAX_LINE];
fopen_s(&pFile, "test.cpp", "r");
if (pFile == NULL)
{
printf("Could not open file for reading.\n");
return 1;
}
while (fgets(buf, MAX_LINE, pFile))
{
printf("%s", buf);
}
fclose(pFile);
}