Reputation: 25
Currently learning the C programming language, I'd like to get in practice some of my knowledge in pointers and file writing. I chose so to write a little software, however, it does not write into the file, there is the the code below.
#include <stdio.h>
#include <string.h>
#define INIT_FAILED 0
#define INIT_SUCCESS 1
int init(char filename[], FILE* logFile);
int init(char filename[], FILE* logFile){
FILE* fileToWrite = NULL;
char dir[] = "logs\\";
strcat(dir, filename);
fileToWrite = fopen(dir, "w");
if(fileToWrite!=NULL){
\\ I think the error is on this line below, but I'm not able to determine why
*logFile = *fileToWrite;
return INIT_SUCCESS;
} else{
return INIT_FAILED;
}
}
int main(int argc, char* argv[]){
char filename[] = "log";
FILE* logFile = malloc(sizeof(FILE));
if(logFile == NULL){
return 0;
}
if(init(filename, logFile)){
fputc('A', logFile)
}
}
I would obviously take with pleasure every suggestions to a better readability of my code.
Thank you.
Upvotes: 1
Views: 195
Reputation: 34585
I've made some corrections to the code, shown by comments. It's not necessary to allocate memory for a single pointer. You already need a pointer to a pointer as the function argument, so it just complicates things. This passes the address of the file pointer to the function, so it can set the variable in main
.
Note that your string would overflow, I added some spare length, although this quick fix could be improved, perhaps with strncat
.
#include <stdio.h>
#include <string.h>
#define INIT_FAILED 0
#define INIT_SUCCESS 1
int init(char filename[], FILE** logFile);
int init(char filename[], FILE** logFile){ // double star
FILE* fileToWrite = NULL;
char dir[100] = "log\\"; // enough length for strcat
strcat(dir, filename);
fileToWrite = fopen(dir, "w");
if(fileToWrite!=NULL){
*logFile = fileToWrite; // remove *
return INIT_SUCCESS;
}
return INIT_FAILED;
}
int main(int argc, char* argv[]){
char filename[] = "log.txt";
FILE* logFile; // remove memory allocation
if(init(filename, &logFile)){ // pass address of the FILE* pointer
fputc('A', logFile); // ; was missing
fclose(logFile); // tidy up
}
}
Upvotes: 2
Reputation: 35
FILE* fileToWrite = fopen("yourfilename.txt", "wr/wb/eb/a...");
if (fileToWrite==NULL){
perror(NULL);
exit(1);
}
Upvotes: 0
Reputation: 67516
IMO you overcomplicate simple things. You do not have to return status as the status is your fopen
result.
FILE *init(const char filename[])
{
/* ... */
return fopen(dir, "w");
}
and then
if((logFile = init(filename))){
fputc('A', logFile)
}
Upvotes: 2