Not to bother anyone, but i have ran into an issue with a class of mine, somehow when i write to a file with the FILE*
and fprintf()
function i don't get any text in my text file that i created, i have searched all over youtube and i don't know what i'm doing wrong, because my code is the same.
Heres a copy of my .c and .h code:
main.c :
#include <iostream>
#include "../include/include.h"
using namespace std;
int main() {
write_file wf("test.txt");
wf.write_line("Hello, world!");
return 0;
}
include.h:
#ifndef INCLUDE_H
#define INCLUDE_H
#include <iostream>
class write_file {
public:
write_file(const char *file_name) {
FILE* fp = fopen(file_name, "w");
}
void write_line(const char *line) {
fprintf(fp, "%s\n", line);
}
void close() {
fclose(fp);
}
private: FILE* fp;
};
#endif /* include.h */
CodePudding user response:
Main issue:
To fix your issue, you have to remove the local fp
variable that shadows the class member.
When the compiler sees FILE *fp
in your method, it uses a separate variable and is not referring to the one in your class instance.
Change the method definition to:
write_file(const char *file_name) {
fp = fopen(file_name, "w");
}
Additional points I really ought to comment on:
You never call
close
. Mishandling resources is one of the most common mistakes in C & CPP. Make sure to implement a destructor that callsclose
. If you do that, make sure to improve theclose
implementation to handle multiple calls.Consider using standard CPP classes for interacting with files, specifically
ifstream
andofstream
. Those handle a lot of the fuss automagically for you.Please don't use
.c
as a file extension. This is really odd. Most CPP developers use.cpp
or.cc
for CPP source files.I might be saying that because I'm not a gen-Z kid, but please don't search Youtube for programming tutorials. Searching text-based sources is so much more efficient. Learn how to use cplusplus or cppreference instead.