Thread: Setting a pointer to file data

  1. #1
    Registered User
    Join Date
    Mar 2005
    Location
    Bangkok
    Posts
    3

    Setting a pointer to file data

    I was wondering if there was any way of setting a pointer to the data of a file. I would use:

    Code:
    ifstream name (argv[1])
    That would open the file, but is there any way to make a variable point to the start of "name". The file is ASCII *.txt file. Also, is there a way to delete characters in a file?

  2. #2
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,981
    Welcome to the boards.

    To have a pointer to the files contents, you will have to read the files contents into a buffer. There are many ways to do this. Here's one way to read the entire contents of a file into a dynamically allocated buffer:
    Code:
    #include <fstream>
    #include <iostream>
    #include <memory>
    using namespace std;
    
    int main()
    {
        // open the stream as binary so we can get the size of the file
        ifstream f("input.txt", ios::in | ios::binary); 
        if (!f)
        {
            cout << "Failed to open" << endl;
            return 1;
        }//if
    
        // get the size of the file
        f.seekg(0, ios::end);
        size_t fsz = f.tellg();
        f.seekg(0, ios::beg);
    
        // allocate room for the file's contents and a null terminator
        auto_ptr<char> fp_ap(new char[fsz + 1]);
        char *fp = fp_ap.get();
    
        // read in the whole file
        f.read(fp, fsz);
        f.close();
        if (!f.good())
        {
            cerr << "Failed to read" << endl;
            return 2;
        }//if
    
        // null terminate the entire file contents as a string
        fp[fsz] = 0;
    
        cout << fp << endl;
    
        return 0;
    }//main
    gg

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-21-2008, 11:19 PM
  2. Problems passing a file pointer to functions
    By smitchell in forum C Programming
    Replies: 4
    Last Post: 09-30-2008, 02:29 PM
  3. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 05:02 AM
  4. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 09:32 AM
  5. Replies: 1
    Last Post: 09-30-2001, 07:45 AM