Read Multiple Lines of a File

C#Coder 0 Tallied Votes 4K Views Share

Adding this because it took literally an hour of searching before I found a code sample using fscanf that read more than just the first line of a file.

This code assumes you're reading a file line by line that has the angle (int) followed by the Sine Value of that angle (double);

#include <stdio.h>

void main()
{
	//Define the arrays for angle and sine
	int a[25];
	double s[25];

    //Grab the filename
	char* name = new char[];
	printf("Load Sine Values\nFile Name: ");
	gets(name);

	//Create the file pointer and open it
	FILE* in = fopen(name,"rt");

	//Read from the file
	int n = 0;
	while(fscanf(in, "%i%lf", &a[n], &s[n]) == 2) n++;

	//Display Proof
	printf("\nLoaded %i entries from %s\n", n, name);
	printf("---------------------------------------\n");
	for(int k=0; k<n; k++)
	{
		printf("%5i%12.6f\n", a[k], s[k]);
	}

	//Close the file
	fclose(in);

	printf("Press Any Key to Continue...");
	char temp[1];
	gets(temp);
}
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.