Mar 30, 2012 at 4:44am UTC
I HAVE MADE A C++ CODE
in which when i open files in read mode it doesnt work while when i open it in write mode it works ...the files i want 2 read already exists. also i am using g++ compiler. the program shows no error ..compiles but doesnt run !!
the only difference which makes program run is
pfile=fopen(cs,"w+");
instead of
pfile=fopen(cs,"r");
where cs stores the file name 2 be read .
Mar 30, 2012 at 5:04am UTC
This is my code... i have made the portion in bold which needs to be taken care of !!
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main ()
{
FILE *pFile1;
FILE *ff;
FILE *pFile;
int a[2000],A[2000];
float b[2000],c[2000],d[2000],e[2000],B[2000],C[2000],D[2000],E[2000];
pFile = fopen ("PS_KAND.sum","r");
int i=0;
while (!feof(pFile))
{
fscanf (pFile, "%f", &b[i]);
fscanf (pFile, "%f", &d[i]);
//fscanf (pFile, "%f", &c[i]);
//fscanf (pFile, "%f", &d[i]);
//fscanf (pFile, "%f", &e[i]);
i++;
cout<<"level1"<<endl;
}
cout<<"i="<<i<<endl;
fclose (pFile);
string st1 = "data";
string ext = ".dat";d
string filename;
cout<<"*******************************";
for(int j = 1; j < 30; j++)
{
stringstream ss;
ss << j;
filename = st1 + ss.str() + ext;
const char * cs = filename.c_str ();
cout<<cs<<endl;
cout << filename <<" opened\n";
pFile1 = fopen (cs,"r"); //THIS IS THE COMMAND CAUSING PROBLEM
if (pFile1==NULL)
{cout<<"oh my god "<<endl;}
int z=0;
while (!feof(pFile1))
{
fscanf (pFile1, "%d", &A[z]);
fscanf (pFile1, "%f", &B[z]);
fscanf (pFile1, "%f", &C[z]);
fscanf (pFile1, "%f", &D[z]);
fscanf (pFile1, "%f", &E[z]);
z++;
}
cout<<"z="<<z;
fclose (pFile1);
float p=0.0,q=0.0,r=0.0;
float cr=0.0,s=0.0;
for(i=0;b[i]<=3;i++)
{
p=p+d[i]*D[i];
q=q+((d[i]*d[i])+(D[i]*D[i]));
r=r+((d[i]+D[i])*(d[i]+D[i]));
}
cr=(2*p)/q;
s=r/(2*q);
if ((cr>0.0001)||(s>0.00008))
{
ff=fopen("bestmodels.dat","a");
fprintf(ff,"%s \t",cs);
fprintf(ff,"%e \t",cr);
fprintf(ff,"%e \t",s);
fprintf(ff," \n");
}
fclose (ff);
}
return 0;
}
Mar 30, 2012 at 2:13pm UTC
can u not use ifstream?
Im a bit rusty on the coding for sure - just picked it back up literally yesterday
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
for (int j = 1; j < 30; j++)
{
stringstream ss;
ss << j;
filename = st1 + ss.str() + ext;
const char * cs = filename.c_str ();
cout<<cs<<endl;
cout << filename <<" opened\n" ;
ifstream inFile;
inFile.open(cs.c_str,std::ios::in); //THIS IS THE COMMAND CAUSING PROBLEM
int z=0;
string in;
if (inFile.is_open){
while (getline(inFile, in)
{
z++;
}
cout<<"z=" <<z;
inFile.close();
itd be easier if i knew what kind of data you had and how you needed to parse it
Last edited on Mar 30, 2012 at 2:15pm UTC
Mar 30, 2012 at 2:45pm UTC
Since it works when you create the file with "w+" but not when you try to open with "r", I would guess the file is not where your program is looking for it.