writing to a file

Hi all,

I'm a beginner to C++, about 4 days into learning it.
I've used Matlab for the last 3 years, and it has made me lazy with all its built in functions and type-non-fussy variables. So I'm learning C++ :)

I've made a program to read in a .csv file, the user selects the headers they want extracted and written to another file. e.g. if the original csv has 57 headers, the user might only be interested in columns 2,3,4,6,8,10,27,

I've managed to extract the data from the chosen columns and display them in the cmd window.
I'm storing it as a string. so if the input csv is...

A, B, C, D, E, F,
11, 21, 31, 41, 51, 61,
12, 22, 32, 42, 52, 62,

and the user selected columns 1,3,5, the output is ...

11, 31, 51,
12, 32, 52,

A the point where I'm using
cout << DataStr;
I'm also using
myfile << DataStr
but it's not working.

Here's the section of code below. I've commented out OutputFile as it wasn't working. I copied the example from http://www.cplusplus.com/doc/tutorial/files/
but even this doesn't work... it compiles fine and runs no probs so i'm stuck as to where the problem is... :(


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
    //ofstream OutputFile; //open output file
    //OutputFile.open ("DAPout.txt"); //create output file
    
    ofstream myfile;
    myfile.open ("example.txt");
    myfile << "Writing this to a file.\n";
    myfile.close();
    
    
    cout<<"Output file created?";
    system("PAUSE");
    
    read.open (argv[1]);
     if (read.is_open()) { //if it's open
        getline (read,line);  //skip the first line, they are headers
        getline (read,line);  //skip the second line, they are units
        while ( read.good() )  //while it's still open
        {
        getline (read,line);  //read the data from 'read' obj, store in 'line'
        
        DataStr = DataFromLine(line, ColsToExport, HEADER_LENGTH, DelimChar, NumToFetch);
        cout<<"Concat Str " <<DataStr<<"\n";
        //OutputFile << DataStr; //write extracted data
        
        }
     } else {
        cout<<"Failed to read input file \n";  //quit if can't read an input file
        return EXIT_SUCCESS;
     }
 read.close();         //close the inputfile
 //OutputFile.close();   //close the output file 
Update / shameless bump

I tried creating the file right at the start of the program when the headers in the .csv are analysed. Writing to the OutputFile works inside the IF but not outside....

I've created a small test prog that writes to a file from inside an IF and outside it. I can't for the life of me see what I'm missing :(

p.s. please forgive any messy or inefficient code, still getting used to it!

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
40
41
 //input a test string to write to file
 string strin;
 getline(cin,strin);
 ofstream OutputFile;            //open output object
 OutputFile.open ("DAPout.txt"); //create output file    

 read.open (argv[1]); //Opens the file drag'n'dropped onto the .exe
 
//==========================================================
// This section is about extracting the header data
//==========================================================
 if (read.is_open()) { //if it's open
       getline (read,line);  //read the data from 'read' obj, store in 'line'
       
       //user enters the char used as delimiter
       cout<<"Enter Delimiter char :";
       cin>>DelimChar;
      
       //find the length of the header to deal with differnt files
       HEADER_LENGTH = FindLineLength(line,DelimChar);
       cout<<"Number of headers in the file = "<<HEADER_LENGTH<<"\n";
 
       found=line.find(DelimChar);  //find the first delimiter
       delim[0]=found;     //store the first location of delimiter
       
       for (int n=1;n<=HEADER_LENGTH;n++) {
           found=line.find(DelimChar,found+1); //finds the next delimiter
           delim[n] = found;            //logs the locations
           if (found>line.size()) break; //exit loop if loc is > length of input line
       }
 } else {
      cout<<"Failed to read input file \n";  //quit if can't read an input file
      OutputFile << strin;   //this works
      OutputFile.close();   //this works
      return EXIT_SUCCESS;
 }                                 // end of if (read.is_open())
 
read.close();         //close the input file, don't need it at the mo
 
//     OutputFile << strin;  //this doesn't!
//     OutputFile.close();   //this doesn't! 
You can certainly can open an output file, write to it, and close it.

The only thing that comes to my mind is that the file appears where you expect it (and you might not have the right to write there). Try an absolute path

There's no output of course when you return EXIT_SUCCESS; before you actually write anything
Thanks, the code before the return EXIT_SUCCESS; only gets run if there was no input file. I've updated the code a little to try make it clearer as to when the strings get written.

- If I run the program without an input file, "File wasn't read" get saved to "DAPout.txt", and it exits. This is the expected result.

- If I run the program with an input file, "DAPout.txt" doesn't even get created!, and the program continues on through the rest of the code.

The only thing I can think is that it's a problem to do with dragging and dropping a .csv file on the .exe

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 
if (read.is_open()) {
...
 } else {
      cout<<"Failed to read input file \n";  //quit if can't read an input file
      OutputFile << "File wasn't read";   //this works
      OutputFile.close();     //this works
      return EXIT_SUCCESS;
 }

read.close();             //close the input file, don't need it at the mo
OutputFile << "File was Read in OK";  //this doesn't!
OutputFile.close();    //this doesn't! 

...//rest of the code 



EDIT::

Yeah it appears to be linked to my use of
read.open (argv[1]) - Fails to write the data after the IF
read.open ("DAPshort.csv"); - Succeeds to write the data after the IF

Can anyone elaborate as to why?

Last edited on
First: the streams do work that's granted.

So like i suggested before try it with absolute pathes (without drag and drop) and where you know you have read and write acess. Then try that drag and drop without additional code. Add line by line until it doesn't work anymore...

A candidate for a failure is the for loop on line 26/28.

The streams are use a million times. So they're not the culprit. Maybe you're messing with the stack and/or heap.
Topic archived. No new replies allowed.