64,654
社区成员
发帖
与我相关
我的任务
分享
#include <string>
#include <iostream>
#include <sstream>
#include <fstream>
using namespace std;
int main()
{
fstream file("D:\\in.txt", ios::in);
int num_line=0; //添个变量记录读取的行数就可以啦
if(!file)
{
cerr<<"error"<<endl;
exit(1);
}
cout<<"Please input the line you want to find:";
int x;
cin>>x;
string line;
while(getline(file, line))//读文件
{
num_line++;
istringstream stream(line);
if(num_line==x)
cout<<num_line<<":"<<line<<endl;
}
return 0;
}
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
void print_line(int line_no)
{
fstream file("in.txt", ios::in);
if(!file)
{
cerr<<"error"<<endl;
exit(1);
}
string line;
int no = 1;
bool flag = false;
while(getline(file, line))//读文件
{
if(no == line_no)//判断是否要打印的行
{
cout<<line<<endl;
flag = true;
break;
}
++no;
}
if(!flag)//若没有这行,输出提示信息
cout<<"no this line!"<<endl;
}
int main()
{
print_line(2);//打印第二行
return 0;
}
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream file("in.txt", ios::in);
int num_line=0; //添个变量记录读取的行数就可以啦
if(!file)
{
cerr<<"error"<<endl;
exit(1);
}
string line;
while(getline(file, line))//读文件
{
num_line++;
if(strstr(line.c_str(), "小白"))//判断是否为小白
cout<<num_line<<":"<<line<<endl;
}
return 0;
}
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream file("in.txt", ios::in);
if(!file)
{
cerr<<"error"<<endl;
exit(1);
}
string line;
while(getline(file, line))//读文件
{
if(strstr(line.c_str(), "小白"))//判断是否为小白
cout<<line<<endl;
}
return 0;
}
小红
小白
小黄
小白
#include <string.h>
#include <stdio.h>
int main(void)
{
FILE *stream;
char msg[] = "this is a test";
char buf[20];
if ((stream = fopen("DUMMY.FIL", "w+"))
== NULL)
{
fprintf(stderr,
"Cannot open output file.\n");
return 1;
}
/* write some data to the file */
fwrite(msg, strlen(msg)+1, 1, stream);
/* seek to the beginning of the file */
fseek(stream, 0, SEEK_SET);
/* read the data and display it */
fread(buf, strlen(msg)+1, 1,stream); /*这里读到buf里以后,在判断是不是回车换行,也就是buf[i]=10*/
printf("%s\n", buf);
fclose(stream);
return 0;
}