How to use a file in a function

Hello, i am trying to use a variable of a file on a function away from the main function, and writing something, but the program crashes without typing anything on the file, how could I write something without initializing a variable on the funcition?

I have tried using pointer to the variable and I`m prettty sure that there is the failure, this is my code:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void cambio(FILE *a);
int main(){
    FILE *archivo;
    char name[20],lec;
    std::cout<<"Type the name of the file: ";
    std::cin>>name;
    archivo=fopen(name,"w+");
    cambio(archivo);
    while(feof(archivo)==0){
        lec=fgetc(archivo);
        std::cout<<lec;
    }
}
void cambio(FILE *a){
    fputs("Añadido",a);
}
Last edited on
Hello unailopez21,

Are you trying to write a C or C++ program??

Andy
Try this as the mix of C/C++. However if this is supposed to be C++, why use C file handling?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <iomanip>
#include <cstdio>

void cambio(FILE* a);

int main() {
	char name[20] {};

	std::cout << "Type the name of the file: ";
	std::cin >> std::setw(20) >> name;

	FILE* archivo = fopen(name, "w+");
	if (archivo == NULL)
		return (std::cout << "Cannot open file\n"), 1;

	cambio(archivo);

	fseek(archivo, 0, SEEK_SET);

	for (char lec; (lec = fgetc(archivo)) != EOF; ) {
		std::cout << lec;
	}
}

void cambio(FILE* a) {
	fputs("Añadido\n", a);
}


which gives:


Type the name of the file: cambio.txt
A±adido

Last edited on
Topic archived. No new replies allowed.