0

I having 2 problem with file handling .

  1. File(txt) is not creating using fstream.Here is my code
#include<iostream>
#include<conio.h>
#include<fstream>

void main()
{char string[80];
   int len;

std::cout<<"Enter a string ";

std::cin>>string;

 len=strlen(string);

std::fstream file;

file.open("RO1.TXT",std::ios::out|std::ios::in);

for(int i=0;i<len;i++)

file.put(string[i]);

file.seekg(0);

char ch;

while(file)

{file.get(ch);

std::cout<<ch;

}
  file.close();
getch();
}

The problem there is no file is created of the name RO1.TXT is my fstream corrupted?

2.If i build using ofstream and ifstream then file is creating but an extra character is being displayed code

   #include<iostream>
#include<conio.h>
#include<fstream>

void main()
{std::ofstream file;
char string[80];
int len;
file.open("RO1.TXT");

std::cout<<"Enter a string ";
std::cin>>string;
 len=strlen(string);

for(int i=0;i<len;i++)
    file.put(string[i]);
file.close();
std::ifstream file1;
file1.open("RO1.TXT");
char ch;
while(file1)
{file1.get(ch);
std::cout<<ch;
}
file1.close();
getch();
}

The problem is extra character is being displayed

Freedom911
  • 610
  • 2
  • 12
  • 26

3 Answers3

2

The last character is displayed twice because you are checking for file stream errors before reading from the file (i.e., before reading end-of-file). You need to check for an error after getting the character.

zennehoy
  • 6,405
  • 28
  • 55
2
while (file1)
{
    file1.get(ch);
    std::cout<<ch;
}

is wrong

while (file1.get(ch))
{
    std::cout<<ch;
}

is right.

Your version is wrong beceause it's only after you try to read and fail that file1 becomes false. This is why you get a repeated character at the end of your file. You call file.get one more time than you have characters in the file but because you don't check for an error at the right place you also call std::cout<<ch one more time than you have characters in the file.

Sometimes seems that every single programmer in the world makes this mistake when they are starting out.

john
  • 85,011
  • 4
  • 57
  • 81
1

You need to check if the ifstream is still valid when you read from it; You read and then display, but if the stream has ended... Try this:

std::ifstream file1;
file1.open("RO1.TXT");
char ch;
while(file1.good())
{
   file1.get(ch);
   if (file1.good())
    std::cout<<ch;
}

UPDATE

This may help you with the first problem:

std::fstream doesn't create file

You have to remove std::fstream::in from your mode argument, or specify std::fstream::trunc as it's said in the above link

Community
  • 1
  • 1
asalic
  • 949
  • 4
  • 10