tags:

views:

262

answers:

1

I am using Visual Studio 2005 (C\C++).

I am passing a string into a function as a char array. I want to open the file passed in as a parameter and use it. I know my code works to an extent, because if I hardcode the filename as the first parameter it works perfectly.

I do notice if I look at the value as a watch, the value includes the address aside the string literal. I have tried passing in the filename as a pointer, but it then complains about type conversion with __w64. As I said before it works fine with "filename.txt" in place of fileName. I am stumped.

void read(char fileName[50],int destArray[MAX_R][MAX_C],int demSize[2])
{
    int rows=0;
    int cols=0;
    int row=0;
    int col=0;
    FILE * f = fopen(fileName,"r");
...

The calling function code is:

char in_filename[50];
int dem[MAX_R][MAX_C]; 
int dem_size[2];
get_user_input( in_filename);
read(in_filename, dem, dem_size );

In the watch I added for filename the correct text appears, so the data is getting passed in.

+3  A: 

If you're using fopen() then you're coding in C, not C++. Also, this is not how you pass arrays to functions. The syntax for the parameter list is

void f(char arr[], unsigned int arr_size);

In the case of multidimensional arrays you must specify the size of the right-most dimension explicitly:

void f(char arr[][20], unsigned int arr_size);

That said, try changing the parameter from char fileName[50] to char* fileName.

wilhelmtell
My mistake - changing the parameter to char * filename succeeds in compile, however the File pointer is invalid, and causes errors when fscan attempts to use it.
Josh
show us the code that calls the function.
wilhelmtell
Are you sure the file with that filename exists? Are you sure your working directory is the directory where the file resides?
wilhelmtell
I added the calling code in the question.And yes, I can put "filename.txt" in place on filename and it works fine. This is the same string literal being passed into the function that I see in the watch if i add a watch for filename.
Josh
If the file exists, are you on a Unix (-like) platform? If so, get the output from `getcwd()` (which is in header `unistd.h`) and check it's the directory where the file is. If you're on Windows then the function is `_getcwd()` and I believe it's in header `direct.h`
wilhelmtell
I got it figured out. It was my reading in that was the problem. I was including the newline in my read input. After changing this, and taking your advice on the parameter change it worked like a charm.Thankyou for your advice and help, I very much appreciate it.
Josh
@Josh: You should test the return value of `fopen()` - if returns `NULL`, then do `perror("fopen");` and you'll get a nice error message telling you what the problem is - which often helps a great deal in tracking down problems like this.
caf
I didn't know that. Thanks for the tip, caf!
Josh