C++中如何读取一个文件。

一段小程序,如何读取一个TXT文档。
一个名为name的文档。

# include "stdio.h"
# include "iostream.h"
# include "string.h"
void main()
{
    //打开文件name.txt且为只读模式
    //name.txt保存在当前文件夹下
    FILE *file=fopen("name.txt","r");
    //验证指针是否为空
    if(file==NULL)
    {
        cout<<"fopen err\n";
    }
    char name[100]={0};
    while(1)
    {
        //必须注意,当一个指针获取的值作为判断条件是一定要先清空存储
        memset(name,'\0',sizeof(name));
        //将文件的字符传递到字符串中
        fgets(name,100,file);
        //当name获取的值为空的时候,跳出循环
        if(0==strlen(name))
        {
            break;
        }
        cout<

你可能感兴趣的:(C++)