I am trying to store data from two variables in a text file .. and then try to get the data back and output it on screen but somehow the following program is not working as supposed to be.

I first enter data in the two variables n1 and n2 .
then i open the file to write data to it ..
then i open the file again to read data from it .. (but data isnt outputted well)

#include<stdio.h>
int main()
{
	char buffer[3];
	int n1, n2;
	scanf("%d",&n1);
	scanf("%d",&n2); 
	FILE *input =fopen("lilly.txt","w+");
	fprintf(input, "%d\n", n1);
	fprintf(input, "%d\n", n2);
	fclose(input);
	
	FILE *output =fopen("lilly.txt","r");
	printf("\n\nN1          = ");
	fgets(buffer, 0, output);
	printf("%s", buffer);
	printf("\n\n1N2 = "); 
	fgets(buffer, 1, output);
	printf("%s", buffer);
	fclose(output);
	getchar();
	getchar();
	return 0;
}

try using fscanf when reading a file, you can use google if your not familiar on using fscanf

Thanks @zeroliken..
Managed to get program to work well..


I couldnt understand what was wrong though in my first attempt.

The integer part of fgets is used for the maximum number of characters to be read (including the final null-character). Usually, the length of the array passed as str is used.

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.