tags:

views:

30

answers:

2

Hi everybody. I`m having problems reading a file address from a txt file. The information seems to be corrupted when I watch it in the debugger. The code is

FILE *parch;
const char * vectorparch[50]; //array with 50 file paths
parch = fopen("/home/irmay/NetBeansProjects/neurona/patrones/patrones.txt", "r");
for(j=0;j<50;j++){
     fread ( vectorparch, sizeof ( char ), 50, parch );
     propagar(vectorparch[j]);      
 }
 fclose(parch);

The file with paths has 50 strings is like this: "/home/irmay/NetBeansProjects/neurona/patrones/10_0.txt","/home/..."

The function propagar is declared void propagar (const char * arch1)

Thank you.

+2  A: 

const char * vectorparch[50]; creates local array of 50 pointers that point ... nowhere. More exactly the values in the array are whatever is there on the stack. You need to explicitly allocate space for each of these 50 strings either with malloc(3) like:

for ( i = 0; i < 50; i++ )
{
    if (( vectorparch[i] = malloc( 50 )) == NULL ) { /* handle error */ }
}

or on the stack like:

const char vectorparch[50*50];

Don't forget to deallocate malloc-ed memory.

Edit:

Looking closer at your code I think you don't even need 50-by-50 space here. You should be just fine with a single character buffer. Something like this:

int j;
FILE* f;
char  buffer[50]; // single buffer for all reads

if (( f = fopen( "filename", "r" )) == NULL ) { /* handle error */ exit( 1 ); }

for ( j = 0; j < 50; j++ )
{
    size_t sz = fread( buffer, 1, 50, f );
    if ( sz == 0 || feof( f ) || ferror( f )) { /* handle error */ break; }
    propagar( buffer, sz ) // NOTE the added buffer size parameter
}

Another note: sizeof( char ) = 1 by definition.

Nikolai N Fetissov
A: 

That's not surprising. This:

const char * vectorparch[50]; //array with 50 file paths

...defines an array of 50 pointers, but not any space for any of those pointers to point AT, so you don't have any space for the individual file names. Based on your call to fread:

fread ( vectorparch, sizeof ( char ), 50, parch );

You're treating each of the as if it was pointing to an array of 50 bytes. That leaves one other minor problem: unless your paths are all exactly 50 bytes long (seems somewhat unlikely) the fread isn't going to do the right thing -- it'll read 50 bytes, regardless of the length of the path. I'd guess it's more likely that your file has one path per line, but the paths aren't necessarily all the same length. In that case, I'd do something like this:

char vectorparch[50][50]; // 50 arrays, 50 characters apiece.

for (j=0; j<50; j++) {
    fgets(vectorparch[j], 50, parch);
    propagar(vectorparch[j]);
}

That may not be what you want though -- you seem to be processing each file path as you read it in. If that's the case, you probably want something more like:

char vectorparch[50]; // one array of 50 characters.
for (j=0; j<50; j++) {
    fgets(vectorparch, 50, parch);
    propagar(vectorparch);
}
Jerry Coffin