C语言 如何读取一个已知txt文件的内容并输出

txt内是字符串,但长度未知,例如:hello,要求把所有字符都提取出来,并输出。

第1个回答  2009-05-17
int main()
{
FILE* file=fopen("D:\\a.txt","r");
char a;
while((a=fgetc(file))!=EOF)
{
printf("%c",a);
}
return 0;
}本回答被提问者采纳
第2个回答  2009-05-17
#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>
#include <memory.h>

#define FILENAME "data.txt"

int main(void)
{
FILE *fp = NULL;
char *content = NULL;
long length = 0;

fp = fopen(FILENAME, "r");

if (fp == NULL)
{
puts("Can not open the file");
return -1;
}

fseek(fp, 0, SEEK_END);
length = ftell(fp);

if (length > 0)
{
fseek(fp, 0, SEEK_SET);
content = (char *)malloc(length + 1);
memset(content, 0, length+1);
fread(content, 1, length, fp);
puts(content);
}

fclose(fp);
return 0;
}
第3个回答  2019-04-22
#include
<string.h>
#include
<stdio.h>
#include
<stdlib.h>
void
main()
{
FILE
*fp=NULL;
int
i;
char
a[41]={'\0'},
ch,
filename[50];
do
{
printf("\n\t请输入要查找关键字的文件:");//这里如果不是在相同目录下要输入完整的路径!
scanf("%s",
filename);
if
((fp=fopen(filename,"r"))==NULL)
printf("\n\t不能打开此文件!
请重新输入!\n");
}while(!fp);
ch=fgetc(fp);
for(i=0;
ch!=EOF;
i++)
{
a[i]=ch;
ch=fgetc(fp);
if(i==39)
{
i=0;
printf("\t%s",
a);
printf("\n\n");
}
}
getchar();
}
第4个回答  2009-05-19
//这个是最简单的方法了~~~

#include<iostream>
#include<numeric>
#include<fstream>
#include<string>
#include<vector>
#include<list>
#include<deque>
#include<algorithm>
#include<stack>
#include<queue>
#include<utility>
#include<sstream>
#include<iterator>
#include<map>
#include<windows.h>
using namespace std;
int main()
{
string way;
cout<<"请输入路径:"<<endl;
cin>>way;
ifstream ll(way.c_str());
vector<string> oo;
string word;
while(ll>>word)
{
oo.push_back(word);
}
cout<<<"读入完成!"<<endl;
//储存到容器
for(vector<string>::iterator ls=oo.begin();ls!=oo.end();++ls)//把容器里的东西输出
{
cout<<*ls<<" "<<flush;
}
system("pause");
return 0;
}
相似回答