- 以下程序执行什么任务?
CPP
#include<iostream> #include<fstream> using namespace std; int main() { ofstream ofile; ofile.open ( "text.txt" ); ofile << "geeksforgeeks" << endl; cout << "Data written to file" << endl; ofile.close(); return 0; } |
- 答复:
The program prints "geeksforgeeks" in the file text.txt
- 描述: 当为ofstream类创建对象时,它允许我们像cout一样写入文件。使用ofstream对象打开文件时,如果文件存在,则内容将被删除,否则将被创建。
- 以下程序执行什么任务?
CPP
#include<iostream> #include<fstream> using namespace std; int main() { char data[100]; ifstream ifile; //create a text file before executing. ifile.open ( "text.txt" ); while ( !ifile.eof() ) { ifile.getline (data, 100); cout << data << endl; } ifile.close(); return 0; } |
- 答复:
The program takes input from text.txt file and then prints on the terminal.
- 描述: 当为ifstream类创建对象时,它允许我们像cin一样从文件输入。getline一次占用整个线路。
- 以下程序的输出是什么?
CPP
#include<iostream> #include<fstream> #include<string> #include<cctype> using namespace std; int main() { ifstream ifile; ifile.open ( "text.txt" ); cout << "Reading data from a file :-" << endl ; int c = ifile.peek(); if ( c == EOF ) return 1; if ( isdigit (c) ) { int n; ifile >> n; cout << "Data in the file: " << n << '' ; } else { string str; ifile >> str; cout << "Data in the file: " << str << '' ; } ifile.close(); return 0; } |
- 输出:
Reading data from a file:-Data in the file:/*content of the file */
- 描述: peek()获取输入流中的下一个字符,而不将其从该流中删除。函数通过首先构造一个对象来访问输入序列。然后,它通过调用其成员函数sgetc从关联的流缓冲区对象(ifile)中读取一个字符,最后在返回之前销毁该对象。
- 运行代码后,对文件内容的更改是什么?
CPP
#include <iostream> #include <fstream> using namespace std; int main () { //create a text file named file before running. ofstream ofile; ofile.open ( "file.txt" ); ofile<< "geeksforgeeks" , 13; ofile.seekp (8); ofile<< " geeks" , 6; ofile.close(); return 0; } |
- 输出:
content of file before:geeksforgeekscontents of the file after execution:geeksfor geeks
- 描述: seekp()用于将put指针移动到相对于参考点的所需位置。使用此函数,流指针将更改为绝对位置(从文件开头开始计数)。在这个程序中,以下内容将写入文件。
ofile<< "geeksforgeeks", 13;
- 然后 奥菲尔。seekp(8) 将指针置于8 th 从一开始定位,然后打印以下内容。
ofile<< " geeks", 6;
- 以下程序的输出是什么?
CPP
#include <iostream> #include <fstream> #include <cctype> using namespace std; int main () { ifstream ifile; ifile.open ( "text.txt" ); //content of file: geeksfor geeks char last; ifile.ignore (256, ' ' ); last = ifile.get(); cout << "Your initial is " << last << '' ; ifile.close(); return 0; } |
- 输出:
Your initial is g
- 描述: 忽略(256“”)从输入序列中提取字符并丢弃它们,直到提取了256个字符,或者其中一个字符与“”比较。这个程序打印文件中第二个单词的第一个字符。
本文由 哈里什·库马尔 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END