Hello,

I have this assignment in C. The problem is that the functions have to be placed in separate files instead of just one. I haven't done that before. It seems code that would have run if the program was written in one file doesn't work when the functions are separated. Why? I've tried this on both Visual Studio 2005 and 2010 on Windows XP with the same result. Here's a small bit of code:

main.c

#include <stdio.h>
#include <stdlib.h>
#include "my_func.h"


int main()
{
	FILE *fp;
	char s[30];
	fp=fn_fop();
	fn_out(&fp);
	fclose(fp);
	printf("\nsuccess\n");
	return 0;
}

my_func.c

#include <stdio.h>
#include <stdlib.h>

FILE *fn_fop()
{
	FILE *fp;
	char fn[30];
	for(;;)
	{
		
		printf("Filename:");
		scanf("%s",&fn);
		if((fp=fopen(fn,"r"))==NULL)
		{
			printf("failure\n");
			getchar();
		}
		else
		{
			printf("file loaded\n");
			return fp;
		}
	}	
}

void fn_out(FILE *fp)
{
	char s[30];
	fgets(s,30,fp);
	fflush(fp);
	printf("%s",s);
}

my_func.h

FILE *fn_fop();
void fn_out(FILE *fp);

The program crashes at fgets in fn_out. It seems to me that the program crashes every time I try to do anything with a file opened in a different function. Except for this one time: When I try to read from the file in main combined with fn_fop it works. But if the file is opened by a function like the following it will crash when accessed in main.

int fn_fop2(FILE *fp)
{
	for(;;)
	{
		char fn[30];
		printf("Filename:");
		scanf("%s",&fn);
		if((fp=fopen(fn,"r"))==NULL)
		{
			printf("failure\n");
			getchar();
		}
		else
		{
			printf("file loaded\n");
			return 0;
		}
	}	
}

Why is this happening? What's wrong?
I'm sorry if my explanation was not sufficient. Thanks in advance for your time!

You didn't pass your file pointer into fn_out() . You created another one which was destroyed when the function ended. Pass fp into your open function.

Also, see this about scanf() and this about fflush()

You didn't pass your file pointer into fn_out() . You created another one which was destroyed when the function ended. Pass fp into your open function.

oh god...

Thanks!

Also, see this about scanf() and this about fflush()

I've read those articles- Things to Avoid in C/C++ but I have to use standard libraries... so I guess I don't have much of a choice...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.