avr39-ripe

fileIOBase

May 4th, 2020
1,513
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.51 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3.  
  4. int main()
  5. {
  6.     std::ofstream outf;
  7.  
  8.     //std::ios::app - append to file
  9.     //std::ios::ate - at the end - go to the end of file
  10.     //std::ios::binary - open file in binary mode
  11.     //std::ios::in - open file to read - input mode default for ifstream
  12.     //std::ios::out - open file for writing - output mode default for ofstream
  13.     //std::ios::trunc - delete file if exist
  14.  
  15.     outf.open("file.txt");
  16.     if (!outf) { std::cout << "IO ERROR! cannot open file!\n"; return 1; };
  17.  
  18.     //outf << "Hello, from C++ file io app!\n";
  19.     //outf << "One more line of text saved in file\n";
  20.     //outf << "Last line! Thats all for now!\n";
  21.     //int num{ 100500 };
  22.  
  23.     //for (int i{0}; i < 4; ++i)
  24.     //{
  25.     //  std::cout << (int)*((uint8_t*)(&num + i)) << '\n';
  26.     //};
  27.  
  28.     float val{};
  29.     for (int i{0}; i < 10; ++i)
  30.     {
  31.         val = ((float)i / (rand() % 100 + 1));
  32.  
  33.         std::cout << "Line number: ";
  34.         std::cout << i << '\n' << val << '\n';
  35.         outf << "Line number:\n";
  36.         outf << i << ' ' << val << '\n';
  37.     }
  38.  
  39.     outf.close();
  40.  
  41.     std::ifstream inf;
  42.     inf.open("file.txt");
  43.     if (!inf) { std::cout << "IO ERROR! cannot open file!\n"; return 1; };
  44.  
  45.     std::cout << "\nTry to read file content: \n";
  46.     char buf[200];
  47.     int numI{};
  48.     float numF{};
  49.  
  50.     while (!inf.eof())
  51.     {
  52.         inf.getline(buf,200);
  53.         //std::cout << buf << '\n';
  54.         inf >> numI;
  55.         if (inf.fail()) break;
  56.         inf >> numF;
  57.         if (inf.fail()) break;
  58.         std::cout << buf << ' ';
  59.         std::cout << numI << ' ' << numF << '\n';
  60.         inf.ignore(100, '\n');
  61.     }
  62.  
  63.     inf.close();
  64.  
  65. }
Advertisement
Add Comment
Please, Sign In to add comment