Manipulating a file in C++

Ok I found this code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
using namespace std;
  int main (void)
      {
      size_t len = 0 ;
    const char a[] = "C:\\Users\\Sage\\Desktop\\Gfx Stuff\\metaknightcopy.bmp";//this is the file
    const char b[] = "F:\\PICTURE\\metaknightcopy.bmp";// this is where I want them to use cin
      char buffer[BUFSIZ] = { '\0' } ;
       
      FILE* in = fopen( a, "rb" ) ;
      FILE* out = fopen( b, "wb" ) ;
       
      if( in == NULL || out == NULL )
      {
      perror( "An error occured while opening files!!!" ) ;
      in = out = 0 ;
      }
      else // add this else clause
      {
      while( (len = fread( buffer, BUFSIZ, 1, in)) > 0 )
      {
      fwrite( buffer, BUFSIZ, 1, out ) ;
      }
       
      fclose(in) ;
      fclose(out) ;
       
      if( remove(a) )
      {
      printf( "File successfully moved. Thank you for using this mini app" ) ;
      }
      else
      {
      printf( "An error occured while moving the file!!!" ) ;
      }
      }
       
      return 0 ;
      }
and I Know how that it works. But I want to make it so it can use cin How do I do this??
Assuming you don't want to just use the Windows API function CopyFile, you need to use file streams.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <fstream>
#include <iostream>

int main( int argc, char * argv[] )
{
    if( argc == 3 )
    {
        try
        {
            std::ifstream input( argv[1], std::ios_base::binary );
            if( !input.good() )
            {
                throw std::runtime_error( "Can't open input file!" );
            }

            std::ofstream output( argv[2], std::ios_base::binary );
            if( !output.good() )
            {
                throw std::runtime_error( "Can't open output file!" );
            }

            char block[1024];
            while( !input.eof() )
            {
                input.read( block, sizeof( block ) );
                output.write( block, input.gcount() );
            }
        }
        catch( std::exception const & e )
        {
            std::cerr << e.what() << std::endl;
        }
    }

    return 0;
}


Note that it's possible to encounter errors reading from input and writing to output whilst inside that loop, so you should really also check for errors in there by checking they are both still good after the copy.

Best wishes,
CC
Last edited on
Topic archived. No new replies allowed.