954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

handling files through functions; program crashes

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!

d_panayotov
Newbie Poster
5 posts since Mar 2011
Reputation Points: 10
Solved Threads: 0
 

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

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

WaltP
Posting Sage w/ dash of thyme
Moderator
10,506 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 
You didn't pass your file pointer into fn_out() . You created another one which was destroyed when the function ended. Passfp 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...

d_panayotov
Newbie Poster
5 posts since Mar 2011
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: