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
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 [].
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.
I know this question has been asked, but the answers I looked at didn't really apply to my case. At the end of my program, a bunch of files are opened for writing. I've limited the list to just two for simplicity. The variable dirPath is a command line argument passed in at execution.
Here's what I tried first:
FILE *fid_sensory_output;
FILE *fid_msn_output;
fid_sensory_output = fopen(strcat(dirPath,"sensory_output"), "w");
fid_msn_output = fopen(strcat(dirPath,"msn_output"), "w");
This doesn't work because strcat doesn't return a copy of the concatenated strings, but instead appends the 2nd arg to the 1st. When looking up a work around, I found these recommendations, to use strcpy and strcat together, or use sprintf.
I first tried sprintf but was getting an error saying that I was trying to pass an int in where a char * was expected, even though dirPath is declared as a char *. I also tried passing in a string literal with no luck.
I tried using strcat and strcpy in various ways without any success either. Any suggestions?
The only way:
FILE *fid_sensory_output;
char *string;
string=malloc(strlen(dirpath)+strlen("sensory_output")+1);
strcpy(string,dirpath);
strcat(string,"sensory_output");
fid_sensory_output = fopen(string, "w");
free(string);
You can use snprintf for this task. Every string operation should consider buffer size to avoid buffer overflows.
snprintf returns the number of characters written to buffer (not including the string terminator '\0')
FILE *fid_sensory_output;
FILE *fid_msn_output;
char path[MAX_PATH];
snprintf(path, sizeof(path), "%s/%s", dirPath, "sensory_output");
fid_sensory_output = fopen(path, "w");
snprintf(path, sizeof(path), "%s/%s", dirPath, "msn_output");
fid_msn_output = fopen(path, "w");
char temp_dir_path[256];
strcpy(temp_dir_path, dirPath);
fid_sensory_output = fopen(strcat(temp_dir_path, "sensory_output"), "w");
strcpy(temp_dir_path, dirPath);
fid_msn_output = fopen(strcat(temp_dir_path,"msn_output"), "w");
I am writing the code of a program that manages plain text files. The question is how can I generate a file, using fopen(), with a String whose length is X.
What I mean with X is that the user can type just one letter as the name of the file ("a.txt"), but he could also type a very long name ("this_is_my_super_new_file_bla_bla_bla.txt").
I am trying to do it with a linked list, but I do not know how to pass the char part of the node of the linked list to the argument of fopen().
Is there another way to do it? The only thing I do not want to do is to restrict the lenght of the name. If I do it, I would have to reserve memory since the beginning, and it would make my program heavier.
Assuming you have a string (char *) with the file name and you would like to add the ".txt" extension, then you could do something like this:
char *input = "new_file_name";
char *filename = malloc((strlen(input) + 5) * sizeof(char));
sprintf (filename, "%s.txt", input);
FILE *file = fopen(filename, "w");
free(filename);
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