I wish to have a file name as an argument to the C program. I tried all the possible ways in fopen something like the below.
fp = fopen(*argv[2], "r");
Also used "*argv[2]" but did not work. I want to know where I am going wrong so that I can use this correctly. Thanks!
It should be
fp = fopen(argv[2], "r");
Please be aware that argv[0] will contain your exe name(with path), other arguments which you pass will start from argv[1].
Refer to this for more details on using command line arguments in C.
In your main function if you are getting char **argv as the argument, the array subscripting argv[1] automatically turns it into a char * which is expected as an argument by fopen.
fp = fopen(argv[2], "r" )
is enough
argv is an array of character pointers. Indexing this array gives you the strings you've passed on the command line. You don't need further dereferencing with an additional *
fopen takes a char* as argument for the filename:
FILE *fopen(const char *path, const char *mode);
You just need to use it like:
fp = fopen(argv[2], "r"); // if 2nd argument passed is your filename
Related
I'm attempting to open a file with fopen and storing it into a FILE*.
The code I have is as follows:
char path[300];
printf("File name: ");
fgets(path, 300, stdin);
FILE* fp;
fp = fopen(path, "r");
if (fp == NULL) {
printf("file does not exist\n");
}
When I run the above code, I get a file not found error; however, when I hardcode the file name:
fp = fopen("test.txt", "r");
The code works as intended.
I think the issue might have something to do with the data type since fopen requires a const char* for it's parameter. I've tried using char*'s but to no avail.
No, it's much simpler than that. When you use fgets the newline character at the end of the line gets included in the char array. That newline is then messing up your attempt to open the file.
Incidentally fopen does not require a const char* parameter. It requires a parameter which can be converted to a const char*. That includes char* as well as char [].
Why can I not do this?
fopen("%s",stringarray,fpointer);
The above returns an error that says too many arguments to function.
But this works,
fopen("file.txt",fpointer);
How can I get around this problem? Do I have to modify the headers in the code?
You cannot call
fopen("%s",stringarray,fpointer);
because that's not the way fopen works. You don't get to make up the way you want to call a standard function like this -- you have to call it the way the documentation says to. You can't call
fopen("file.txt",fpointer);
either. You have to call something like
fpointer = fopen("file.txt", "r");
assuming that you have declared
FILE *fpointer;
so that fpointer will be your "open file pointer" or "file handle" as you read the file file.txt.
Assuming stringarray is a char * (really a chararray), simply pass it directly into fopen. There's no need to format it with %s, it's already a string.
FILE *fp = fopen(stringarray, "r");
Functions in C take very, very, very specific arguments. fopen takes a filename as a char * and the mode to open the file (read, write, etc...) as another char *. It returns a pointer to the opened file, or NULL if there was an error.
If you did need to do some sort of formatting, you'd use sprintf to do the formatting and pass the result into fopen.
// Allocate memory to store the result of sprintf
char filename[256];
char name[] = "foo";
// filename = foo.txt
sprintf(filename, "%s.txt", name);
// Open foo.txt
FILE *fp = fopen(filename, "r");
fopen (const char *filename, const char *mode)
If you take a look in fopen function, it takes only two arguments as input. So, you cannot use it like fopen("%s",stringarray,fpointer);. For more information about fopen() visit here
As stated in the title, i ask for the user to provide the filename and i use gets to save it in str. Then i try to access the file using the name and the program crashes.
int openFile(FILE *fp){
puts("What's the name of the file (and format) to be accessed?");
char str[64];
gets(str);
fp = fopen((const char *)str, 'r');
...
return 0;
In main:
FILE *fp; // file pointer
openFile(fp);
The filename i enter (data.txt) is indeed in the same directory as the rest of the project so that should not be the problem. I've tried testing if the file is opened correctly (which it should) but it keeps crashing right after i give the name.
The main problem is that you are trying to set an argument passed by value in a function and expect the value to be changed outside. This can't work.
Currently you have:
void openFile(FILE* fp) {
fp = ...
}
int main()
{
FILE* fp;
openFile(fp);
}
But fp in main() is passed as a pointer by value. Which means that inside openFile you are setting a local variable, while the passed one is not modified.
To solve the problem you can:
directly return a FILE* from openFile
accept a pointer to pointer argument to be able to set it, eg void openFile(FILE** fp) and then openFile(&fp)
Mind that the second argument of fopen is a const char* not a single char, "r" should be used.
It should be fp = fopen(str, "r");, because fopen() expects mode as a char * pointing to a string, rather than a single char.
Also, since parameters in C are passed by value, your fp won't get modified after openFile() is called. To get it work, you'll have to rewrite it, and call it by openFile(&fp);. Here is an example:
void openFile(FILE **fp) {
puts("What's the name of the file (and format) to be accessed?");
char str[64];
fgets(str, 64, stdin);
str[strcspn(str, "\n")] = '\0';
*fp = fopen(str, "r");
}
fgets() is used to provide buffer overflow protection.
My program in C reads data in a file in order to initialise variables but it won't open the file. It fails when it reaches fopen. Xcode outputs the following warning for both fopen and printf. I understand the error but I don't know how to correct it, I tried many tricks but it won't do, can anyone help me out ? I just want my program to open Try1.txt.
Incompatible pointer types passing 'char (*)[9]' to parameter of type const char*'
So this is the code inside my main function :
FILE *infile = NULL;
const char infilename [] = "Try1.txt";
infile = fopen(&infilename, "r");
if (infile == NULL)
{
printf("Failed to open file: %s\n", &infilename);
return 1;
}
Note that the program stops before reaching the if loop because it never prints. I tried to initialise the size and to add '\0' at the end of my string too.
It's because of &infilename, which gives you a pointer to the array of characters. Drop the address-of operator and it will work.
Problem
&infilename is a pointer to the array, which means it is a pointer to an object of type char (*)[9].
But, infilename will be a pointer of type char (*), which points to the first element of the array.
Fix
infile = fopen(infilename, "r");
I am trying to find a way to use
FILE * fopen ( const char * filename, const char * mode ); but passing the filename indirectly. i would also like to know how to indirectly call a function with name taken straightly from argv[].I dont want to store the string in a buffer char array. For example:
int main (int argc,char *argv[])
{
FILE *src;
...
src = fopen("argv[1]", "r"); //1st:how to insert the name of the argv[1] for example?
...
function_call(argc,argv); //2nd:and also how to call a function using directly argc argv
...
}
void create_files(char name_file1[],char name_file2[])
{...}
Do i have to store length and the string of chars in order to call a function? (regarding the 2nd question) :)
You can simply use argv[1], it's a char *:
if (argc < 2)
/* Error. */
src = fopen(argv[1], "r");
Same goes for create_files.
create_files(argv[1], argv[2]);
fopen takes a pointer to an array of characters. argv is pointer to an array of pointers to arrays of characters.
fopen(argv[1], "r")
will pass the pointer in the second position of the argv array to fopen.
If you want to pass argc and argv around, just pass them as they are. Their types do not change.