Solved

Open a file with a constructor

Posted on 2004-10-02
6
228 Views
Last Modified: 2012-05-05
I am trying to open a file in the classes contructor. The file is
created and the program even thinks it is open and tries to write to
it with no errors, but when I look at the file it is zero
bytes..nothing was written to it. As a side note this program resides on a Linux box.
 Here is part of my code if anyone
can help me. I do appreciate it.

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include "stdio.h"

using namespace std;

class file_handler
{
       private:
               ofstream outfile;
       public:

               char InventoryNumber[16];
               char ProductName[21];
               char ProductCode[4];
               int  OnHandQuantity;
               int  BackOrderQuantity;
               int  OnOrderQuantity;
               float InventoryEvaluation;
               float AverageCost;
               float SellingPrice;

               file_handler();
               file_handler(string file);
               ~file_handler();
               int write_file();
file_handler::~file_handler()
{
       outfile.close();
}

file_handler::file_handler(string file)
{
       outfile.open(file.c_str(),ios::out|ios::app|ios::binary);
}

file_handler::write_file()
{
   //writing file stuff
}

int main()
{
   file_handler newfile("inventory.dat")
}
0
Comment
Question by:microcoop
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
6 Comments
 
LVL 30

Expert Comment

by:Axter
ID: 12209953
Please post the code that is actually writing to the file.

Post the contents of write_file()
0
 
LVL 30

Expert Comment

by:Axter
ID: 12209964
You should add code, to check if the file has been open successfully.
file_handler::~file_handler()
{
      outfile.close();
      if (!outfile.is_open())
      {
          //Report error
      }
}
0
 
LVL 30

Accepted Solution

by:
Axter earned 500 total points
ID: 12209971
Since your file name does not have a full qualified path, make sure you're looking in the wright path.
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:microcoop
ID: 12210018
Here is the contents of
file_handler::write_file()                        
{
      if(outfile.is_open())                        
      {
            char buffer[10];                        
            

            outfile.write(InventoryNumber, 16);      
            outfile.write(ProductName, 21);            
            outfile.write(ProductCode, 4);            
            
            sprintf(buffer,"%d",OnHandQuantity);      
            outfile.write(buffer, 5);                        
      
            sprintf(buffer,"%d",BackOrderQuantity);
            outfile.write(buffer, 5);                        

            sprintf(buffer,"%d",OnOrderQuantity);      
            outfile.write(buffer, 5);                        

            sprintf(buffer,"%f",InventoryEvaluation);      
            outfile.write(buffer, 8);                              
            
            sprintf(buffer,"%f",AverageCost);                  
            outfile.write(buffer, 7);                              

            sprintf(buffer,"%f",SellingPrice);                  
            outfile.write(buffer, 7);                              

            
      }
      
      return 0;
}

outfile << "anything"; also will not work
I also have put in a check if(outfile.is_open()) and tested it with a cout << "File if open"; inside the if statement and it displays so it thinks the file is open at least. And if I delete the file the constructor does recreate it. It steps through all the writes and thinks, at least that it is writing. But the file is completely empty. Also, as a side note this program originally written with vs.net works prefectly on a windows pc, but when moved to it's destination pc the Linux box. It compiles and everything runs, but it just doesn't actually writes.

Also, I tested opening a different file in main() and then also writing to it from main() and that will work. but when the contructor open a file and a method writes to it. It doesn't actually write.

Lastly, just for reference incase anyone needs it here it the complete code, but it will be cluttered a bit with comments.

//Included Headers

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include "stdio.h"


using namespace std;                  




class file_handler                                                      
{
      private:                                                            
            ofstream outfile;                                          
      public:                                                                  
            
            char InventoryNumber[16];                              
            char ProductName[21];                                    
            char ProductCode[4];                                    
            int  OnHandQuantity;                                    
            int  BackOrderQuantity;                                    
            int  OnOrderQuantity;                              
            float InventoryEvaluation;                              
            float AverageCost;                                          
            float SellingPrice;                                    

            file_handler();                                          
            file_handler(string file);                              
            ~file_handler();                                          
            int write_file();                                          






file_handler::~file_handler()            
{
      outfile.close();                        
}

file_handler::file_handler(string file)      //Constructor to open the file
{
      outfile.open(file.c_str(),ios::out|ios::app|ios::binary);      
}

file_handler::write_file()                        
{
      if(outfile.is_open())                        //Make sure file is open
      {
            char buffer[10];                        //Create a temp buffer for storing the fields to write
            

            outfile.write(InventoryNumber, 16);      //Write Field 1
            outfile.write(ProductName, 21);            //Write Field 2
            outfile.write(ProductCode, 4);            //Write Field 3
            
            sprintf(buffer,"%d",OnHandQuantity);      //Change to a char
            outfile.write(buffer, 5);                        //Write Field 4
      
            sprintf(buffer,"%d",BackOrderQuantity); //Change to a char
            outfile.write(buffer, 5);                        //Write Field 5

            sprintf(buffer,"%d",OnOrderQuantity);      //Change to a char
            outfile.write(buffer, 5);                        //Write field 6

            sprintf(buffer,"%f",InventoryEvaluation);      //Change to a char
            outfile.write(buffer, 8);                              //Write field 7
            
            sprintf(buffer,"%f",AverageCost);                  //Change to a char
            outfile.write(buffer, 7);                              //Write field 8

            sprintf(buffer,"%f",SellingPrice);                  //Change to a char
            outfile.write(buffer, 7);                              //Write field 9

            
      }
      
      return 0;
}

file_handler::check_blank1(char input[16])                  //Field Validator for Field 1
{

      if(*input != '\0' && input != "END")                  //Make sure it isn't empty or time to quit
      {      
            strcpy(InventoryNumber, input);                        //Copy the input to the class variable
      }
      else                                                                  //If it is blank
      {
            cout << "Inventory Number may not be blank";      //display a message and terminate
            exit(1);                                                            //Exit
      }
      return 0;
}

file_handler::check_blank2(char input[21])                  //Validator for field 2
{
      if(*input != '\0' )                                                //Make sure it isn't empty
      {      
            
            strcpy(ProductName, input);                              //copy the input to the class variable
      }
      else                                                                  //If it is blank
      {
            cout << "Product Name may not be blank";      //Display an error message
            exit(1);                                                      //And exit
      }
      return 0;
}

file_handler::check_blank3(char input[4])                  //Validator for field 3
{      
      int d;                                                                  //Temporary storage variable for isalpha
      if(strlen(input) == 3 && input != '\0')                  //Make sure it is three char in length and not empty
      {
            for(int i=0; i<3; i++)                                    //Loop through and make sure it is letters
            {
                  d = isalpha(input[i]);                              //Assign d a number telling us if it is or is not a letter
                  if(d == 0)                                                //If it is a letter
                  {
                        cout << "Product code may have numeric characters" << endl;      //Display an error message
                        cout << "Transaction Terminated";                                          //Display and error message
                        exit(1);                                                                              //And exit
                  }
            }
      }
      else                                                                  //If it isn't 3 characters long
      {
            cout << "Product code must be three characters long" << endl;            //Display and error message
            cout << "Transaction Terminated";                                                      //Display and error message
            exit(1);                                                                                          //And exit
      }

      if(*input != '\0')                                                                                    //If it passes all that and isn't empty
      {      
            input = strupr(input);                                                                        //We know it's letters so upper case it for the user
            strcpy(ProductCode, input);                                                                  //copy this correct value to the class variable
      }
      else                                                                                                      //If it is empty (which is repititve)
      {
            cout << "Product Code may not be blank";                                          //Display an error message
            exit(1);                                                                                          //And exit
      }
      return 0;
}

int file_handler::check_nonneg(int input, int type)                                          //Method to check and int fields for only posistive numbers
{
      if(input == 0)                                                                                          //if the number is zero
      {                                                                              
            input = 0;                                                                                          //Leave it zero
            OnHandQuantity = input;                                                                        //And copy it to the class variable
      }
      else if (input >= 0 && type == 1)                                                            //Check Field 4 for >= 0
      {
            
            OnHandQuantity = input;                                                                        //If it passes copy it to the class variable

      }
      else if (input >= 0 && type == 2)                                                            //Check field 5 for >= 0
      {
            
            BackOrderQuantity = input;                                                                  //If it passes copy it to the class variable
      }
      else if (input >= 0 && type == 3)                                                            //Check field 6
      {
            
            OnOrderQuantity = input;                                                                  //If it passes copy it to the class variable
      }
      else                                                                                                      //Else a negative was found
      {
            cout << "Integers may not be negative";                                                //Display an error message
            cout << "Transaction Terminated";                                                      //Display an error message
            exit(1);                                                                                          //Exit
      }
      return 0;
}

int file_handler::check_float(float input)                                                      //Check field 7
{
      if(OnHandQuantity != 0 && input == 0)                                                      //If the prior on hand != 0 and the new input == 0 then that isn't acceptable
      {
                  cout << "Inventory Evaluation may not be 0 if On-Hand Quantity is also  0";      //Display an error message
                  cout << "Transaction Terminated";                                                                  //Display an error message
                  exit(1);                                                                                                      //Exit
      }
      else                                                                                                                        //Else all is good
      {
            InventoryEvaluation = input;                                                            //copy the value to the class variable
      }
      return 0;
}

int file_handler::avg_cost()                                                                        //Compute our average cost
{
      float  AverageCost_temp;                                                                        //A temp variable used in this method

            if( InventoryEvaluation != 0 && OnHandQuantity != 0)                        //Make sure we are not dividing by zero
            {
                  AverageCost_temp = InventoryEvaluation/OnHandQuantity;                  //Do our computation
            }
            else                                                                                                //If we are about to divide by zero, then let's stop this and just assign zero
            {
                  AverageCost_temp = 0;                                                                  //Assign the zero
            }

            if(AverageCost_temp < 5000)                                                                  //Now check that this ne value is less than 5000

            {
                  AverageCost = AverageCost_temp;                                                      //If it is then assign the new value to the class variable
            }
            else
            {
                  cout << "Average Cost Must Be less than 5000. Please check the Inventory Evaluation and On-hand Quantity."; //Display error message
                  cout << "Average Cost = Inventory Evaluation / On-hand Quantity";                                                                  //Display error message
                  cout << "Transaction Terminated";                                                                                                                  //Display error message
                  exit(1);                                                                                                                                                      //Exit
            }
            return 0;
}

int file_handler::sell_price(float input)                        //Check out sell price, the last field
{
      if(input > AverageCost)                                                //This value must be greater than the average cost
      {
            SellingPrice = input;                                          //If it is then write it to the class variable
      }
      else                                                                        //Else we're losing money
      {
                  cout << "Selling Price must be greater than Average Price.";      //Display an error message
                  cout << "Transaction Terminated";                                                //Display an error message
                  exit(1);                                                                                    //Exit
      }
      return 0;
}      

/////////////////////////////////END OF CASS METHODS/////////////////////////////////


///////////////////////////////////MAIN//////////////////////////////////////////////


int main()                                                            //Main Procedure
{
      file_handler newfile("inventory.dat");            //Inistiate the class and open the file
      
            char stop[16];                                          //Temp variable for main
            char prod_name_temp[21];                        //Temp variable for main
            char prod_code_temp[4];                              //Temp variable for main
            int  on_hand_temp;                                    //Temp variable for main
            int  back_order_temp;                              //Temp variable for main
            int  order_quant_temp;                              //Temp variable for main
            float inv_eval_temp;                              //Temp variable for main
            float sell_price_temp;                              //Temp variable for main
      
      
      while(1 != 0)                                          //This while loop is irrelevant since we stop with "END" in a method
      {
            stop[16] = '\0';                              //Go ahead and set stop to null
            prod_name_temp[21] = '\0';                  //Set prod_name_temp to null also
            


            
            //Welcome Message
            cout << endl << "Enter the inventory information, type END in Inventory Number to quit." << endl;
            cout << "----------------------------------------------------------" << endl;
            //End Welcome Message

////////////////////////////////INVENTORY INFORMATION///////////////////////////////

            cout << "Enter an Inventory Number: ";            //Prompt for Inventory Number
            cin.getline(stop,16);                                    //Accept Inventory Number

            if(strcmp(stop,"END") == 0)                  //Check if the user entered END
            {      

                  cout << endl << "Program Aborted" << endl;      //If the did, display a message
                  cout << "--------------------------------------------------------" << endl;
                  exit(1);                                          //Exit
            }

            newfile.check_blank1(stop);                              //Inventory Number Method

///////////////////////////////END INVENTORY INFORMATION////////////////////////////
            
///////////////////////PRODUCT NAME/////////////////////////////////////////

            cout << "Enter a Product Name: ";            //Prompt for Product Name
            cin.getline(prod_name_temp, 21);            //Accept Product Name
            newfile.check_blank2(prod_name_temp);      //Product Name Method

/////////////////////////END PRODUCT NAME/////////////////////////////////

////////////////////////PRODUCT CODE///////////////////////////////////////

            cout << "Enter a Product Code: ";            //Prompt for Product Code
            cin.getline (prod_code_temp, 4);            //Accept Product Code
            newfile.check_blank3(prod_code_temp);      //Product Code Method

//////////////////////END PRODUCT CODE/////////////////////////////////////

/////////////////////ON HAND QUANTITY////////////////////////////////////

            cout << "Enter the On-hand Quantity: ";            //Prompt for On Hand
            cin >> on_hand_temp;                                    //Accept On Hand
            newfile.check_nonneg(on_hand_temp, 1);            //On Hand Method

/////////////////////END ON HAND QUANTITY////////////////////////////////

/////////////////////BACK ORDERED QUANTITY///////////////////////////////

            cout << "Enter the Back Ordered Quantity: ";      //Prompt for Back Order
            cin >> back_order_temp;                                          //Accept Back Order
            newfile.check_nonneg(back_order_temp, 2);            //Back Order Method

////////////////////END BACK ORDER QUANTITY////////////////////////////////////////

/////////////////////ON ORDER QUANTITY/////////////////////////////////////////////

            cout << "Enter the On Order Quantity: ";            //Prompt for Order Quantity
            cin >> order_quant_temp;                                    //Accept Order Quantity
            newfile.check_nonneg(order_quant_temp, 3);            //Order Quantity Method

/////////////////////END ON ORDER QUANTITY/////////////////////////////////////////

///////////////////INVENTORY EVALUATION///////////////////////////////////////////

            cout << "Enter the Inventory Evaluation: ";            //Prompt for Inventory
            cin >> inv_eval_temp;                                          //Accept Inventory
            newfile.check_float(inv_eval_temp);                        //Inventory Method

///////////////////END INVENTORY EVALUATION////////////////////////////////////////

/////////////////////////////COMPUTE AVERAGE COST//////////////////////////////////

            newfile.avg_cost();                                                //Average Cost Method

/////////////////////////////END COMPUTE AVERAGE COST//////////////////////////////

///////////////////////////////////////SELL PRICE//////////////////////////////////

            cout << "Enter the Sell Price: ";            //Prompt for Sell Price
            cin >> sell_price_temp;                              //Accept Sell Price
            newfile.sell_price(sell_price_temp);      //Sell Price Method

///////////////////////////////////////END SELL PRICE/////////////////////////////

            newfile.write_file();      //Call the method to write to the file

            cin.ignore(); //This allows cin.getline to keep going

      }      //Loop
            
      
      
      //return 0; //Return Nothing

}

////////////////////////////////////////////END OF MAIN///////////////////////////////////
0
 

Author Comment

by:microcoop
ID: 12210022
Also note that the program and file are located in the same home directory on Linux.
0
 

Author Comment

by:microcoop
ID: 12210441
For some reason the destructor isn't closing the file. I Added outfile.flush(); and outfile.close(); and it wrote the buffer to the file and it was fixed. I guess I really don't understand destructors. (
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

737 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question