Results 1 to 7 of 7

Thread: Reading/Writing Files and editing

  1. #1
    Join Date
    Dec 2011
    Location
    -bash
    Posts
    515
    Mentioned
    0 Post(s)
    Quoted
    27 Post(s)

    Question Reading/Writing Files and editing

    So I first create a file and I type in 2 numbers into it. I need to write a c function in a c++ template (so you call the c library (#include <cstdlib> #include <cstdio>)).

    The problem is that I need to create a program that will read the integers from the file I already created (fscanf, fprintf) and then add the 2 integers, create a new file and put the sum into that file.

    Please only limit making this program to:
    fopen() Open a file
    fclose() Close a file (important when writing!)
    fprintf() Print to text stream like printf()
    fscanf() Read from text stream like scanf()
    feof() Returns true if end-of-file is reached
    fgets() Read a line of text from a text stream.

    So that I can actually follow your reasoning.

    Thanks in advance

  2. #2
    Join Date
    Feb 2011
    Location
    The Future.
    Posts
    5,600
    Mentioned
    396 Post(s)
    Quoted
    1598 Post(s)

    Default

    C++ Code:
    #include <cstdio>
    #include <cstdlib>

    void CReadWriteFile(const char* FileNamePath)
    {
        char Buffer[1024]; //You can use ftell and fseek to figure out the file size and dynamically allocate but right now I'm tired.
        int Value1 = 100, Value2 = 200;  //Values to be written.

        FILE* pFile = fopen(FileNamePath, "w+");    //Open the file for reading!

        if (pFile != NULL)
        {
            fprintf(pFile, "%i %i", Value1, Value2);     //Write the two values to the file.
            Value1 = Value2 = -1;                        //Reset the values to check if we actually read the same values back.
            rewind(pFile);   //Move the file pointer back to the beginning of the file since we already wrote and the pointer moves as we write.
            fscanf(pFile, "%i %i", &Value1, &Value2);  //Read the values back.
            fclose(pFile);
            printf("I Read These Two Values: %i && %i.", Value1, Value2);  //Print the values.
        }
    }

    int main()
    {
        CReadWriteFile("C:/Users/Brandon/Desktop/CFile.txt");
    }

    That's how it's done but next time show a little bit of effort and I can push you along from there so that I don't have to write that much when tired. lol.

    Sorry if I didn't use fgets and fputs and eof. I just checked if it's NULL instead and I guess you can probably do "While !eof" or whatever, read. Though since the file isn't large, that's useless! And since I knew you're only writing two values, there's no need for dynamic allocation.
    Last edited by Brandon; 07-04-2012 at 12:50 AM.
    I am Ggzz..
    Hackintosher

  3. #3
    Join Date
    Dec 2011
    Location
    -bash
    Posts
    515
    Mentioned
    0 Post(s)
    Quoted
    27 Post(s)

    Default

    Thanks Brandon, however I have some questions about some of the things you wrote. For example, what is the difference b/w char and const char?

    C++ Code:
    void CReadWriteFile(const char* FileNamePath)

    Another question is in regards to this part:
    C++ Code:
    FILE* pFile = fopen(FileNamePath, "w+");    //Open the file for reading!
    This : FILE*pFile<---What does it do? And what does the "w+" mean?

    Also, do you have to open the file to read the contents or can't you just read the contents by fscanf and output the variables?

  4. #4
    Join Date
    Feb 2011
    Location
    The Future.
    Posts
    5,600
    Mentioned
    396 Post(s)
    Quoted
    1598 Post(s)

    Default

    Be specific. The difference between char and const char is that char is volatile while const char is non volatile.

    Volatile variables CAN be changed and modified at any time. Non-volatile variables MUST stay the same every where! Forcefully changing them in some cases can cause corruption!

    To change the const correctness of a variable you'd either use the C-style cast aka GodMode cast and should rarely ever be used.. OR you can use C++ style casting.

    C++ Code:
    const char bleh;
    char meh = (char) bleh;   //casts away the constant part via c-style casting.

    char meh = const_cast<char>(bleh);  C++ style casting has 4 kinds. const, dynamic, static, reinterpret.


    Anyway in the code above, I never used const char. I used const char *. There is a difference. char* is a pointer to an array of characters. We both know that an array of characters is equivalent in most cases to a string since strings are just a bunch of characters put togther.

    const char* is an array of characters that will not change during runtime. You can pass values that are not const to a const char* without a cast. You can assign values to a variable from the const char* but modifying the pointer itself is a big no-no.
    C++ Code:
    const char* Bleh = "Brandon";
    std::string Meh = Bleh;     //Assigning to a non const variable.

    const char* Bleh = Meh.c_str();   //Meh is a string. C_str() is to convert it to a const string which can be assigned to a const char*.

    All the of the above is fine. Const char* is just saying that this array of characters can be modified but the pointer to it cannot. Inorder to make sure that the array cannot modify, we do: char* const str = "Brandon"; This string can never ever be changed!

    I could have easily used const std::string or std::string or std::string::c_str(); They'd all work the same.

    Also for the FILE* pFile. That line declares a pointer to a File. A pointer to a file or any object where the size is unknown is known as either a handle or opaque pointer. An opaque pointer is something that you do not have a clue of it's size or what kind of data it points to.

    FILE* pFile is a pointer to a file and it is opaque because I do not know the size of the pointer itself (completely different from file size). AND I do not know what kind of data the pointer points to. All I know is that it points to a file and that is it!

    So first I declare a pointer/handle to a File then I assign it to an open file via fopen. If fopen fails, my pointer will be null. Null pointers are special because you can delete them without harm and you can close them without harm but they're useless because well? We want our file open thus it should not be null if it suceeded.


    w = write only File is created if it does not exist.. If it does, the contents are erased and it's considered a new blank file.

    r = read only. File must exist.

    w+ = read and write at the same time. If the file does not exist, it will create it! if the file already exists, the contents are erased and it's treated as a blank new file.

    r+ = open a file for reading and writing/updating. File must exist!

    a = append to a file. File is created if it does not exist.

    a+ = Open the file for reading and appending. All writing is done at the very end of the file. Hence appending. Creates the file if it doesn't exist already.


    TLDR: File* pFile is a handle to a file. const char* is a string. Usually char* is a c-style string. At least in the context they are use in. Might sound harsh by saying be specific but the difference between char* and char can screw you over so I had to explain.
    Last edited by Brandon; 07-04-2012 at 04:39 AM.
    I am Ggzz..
    Hackintosher

  5. #5
    Join Date
    Dec 2011
    Location
    -bash
    Posts
    515
    Mentioned
    0 Post(s)
    Quoted
    27 Post(s)

    Default

    Sweet, I got it to work lol. This is my first time doing something like this! I am still feeling elated as I write this, so forgive my enthusiasm! Here it is:

    C++ Code:
    //============================================================================
    // Name        : ReadWriteFile.cpp
    // Author      :
    // Version     :
    // Copyright   : Your copyright notice
    // Description : Hello World in C++, Ansi-style
    //============================================================================

    #include <cstdio>
    #include <cstdlib>

    void ReadWrite(const char* filepathName)
    {
        FILE* infile;
        FILE* outfile;

        int Value1, Value2;
        infile = fopen(filepathName, "r");//the filepath is already declared "C:/Users/Chig/Desktop/Input.txt".
        //The ’r’ means we will read file.

        outfile = fopen("C:/Users/Chig/Desktop/Output.txt", "w"); //the output file. This is where our total will be stored
        //The 'w' means we will be writing into this and deleting anything that already exists in it.

        if(infile == NULL) //this will be true if there was an error such as file not existing
        {
            perror("fopen failed");
        }
        else
        {
            printf("File opened successfully.\n");
            fscanf(infile, "%i %i", &Value1, &Value2);
            fclose(infile);
            fprintf(outfile, "%i", Value1 + Value2);
            printf("Operation executed successfully! Open Output.txt in the desktop to view results! \n");
        }


    }

    int main(void)
    {
        ReadWrite("C:/Users/Chig/Desktop/Input.txt");

        return EXIT_SUCCESS;
    }

    Any suggestions or shortcuts are welcome


    Now, as usual, I want to take it a step further. What about when you don't know the exact size of the file you are trying to read? And you want to read that file and copy all the text in it (including numbers and characters alike) into a new file, how would one accomplish this?

  6. #6
    Join Date
    Apr 2007
    Posts
    581
    Mentioned
    1 Post(s)
    Quoted
    2 Post(s)

    Default

    In C++ I believe there is a function for file streams called eof(). You should be able to find it with a quick Google search.

    This is just pseudo code but it would look something like:

    Code:
    while(!file.eof()) {
      file.readintobuffer(buffer, 0, 1024);
      cout << buffer << endl;
    }
    If you're looking for the C-way to accomplish it, I have absolutely no idea.

  7. #7
    Join Date
    Feb 2011
    Location
    The Future.
    Posts
    5,600
    Mentioned
    396 Post(s)
    Quoted
    1598 Post(s)

    Default

    I'm proud and happy you wrote that.
    I didn't even have to explain how to do two files at once! =] Good job on that. Really.

    Now for figuring out the file size, I mentioned fseek/ftell/seekg/tellg before correct?

    fseek/ftell is C code. C++ uses iostreams which append a g to the end and gets rid of the f. the G generally stants for "Get". The F was removed because it's no longer File Get. In Cpp it's stream get.

    Anyway enough about that since you aren't using ios file reading, I will demonstrate ftell/fseek as your code is C-Style file IO.

    C++ Code:
    void GetFileSize(const char* FileNamePath)
    {
        FILE* pFile = fopen(FileNamePath, "rb");  //rb means read in binary mode. You DO NOT need binary mode but it depends on the kind of file. I tend to leave it there.

        if (pFile != NULL)
        {
            fseek(pFile, 0, SEEK_END);  //First we set the pointer to the very end of the file. This is good because when we ask to tell, it will just check where the pointer is.
            long size = ftell(pFile);   //Pointer is at the end of the File. We ask it to tell use the size of the file in bytes!
            fclose(pFile);              //Always remember to close the file. It is a pointer/handle!

            printf("Our File Size In BYTES is: %ld \n", size); //Print our file size in bytes! This is not bits, not megabytes, not megabits. It's bytes.
        }

        //When creating a buffer for the reading, you can do:
        char* Buffer = new buffer[size];    //provided that size is declared in this scope. Currently it is not. It's in the scope of the if statement above.
        //Read the file into the buffer.. Do whatever you want with the data!
        //BUT ALWAYS, and I mean always in capitals: Remember to delete[] that buffer after!
        delete[] Buffer;
    //You most likely also want to reset the file pointer using rewind(pFile); After getting it's size.
    }

    For the guy above, EOF means end of file. That's not getting file size. In Cpp it's istream::seekg and isstream::tellg. ofstream::seekp as well for pointers. While(!EOF) can also give undefined behaviour and cause an infinite loop. It's better to just get file size and read in one fell swoop unless you're tokenizing the data. Neat pseudo though.
    Last edited by Brandon; 07-04-2012 at 06:03 AM.
    I am Ggzz..
    Hackintosher

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •