Firstly, I'll admit I'm new to this (first year programming, be gentle!). I would hugely appreciate help! I've been trying to find an answer for this problem, but my understanding of pointers and their relationship to opening files is somewhat grey.
Description of issue:
I wish to read a bunch of names (as an array of chars) from a file and store them in an array. I had this working before, but now I want to fill my array with names in a different function called get_names(), while handling the file opening in my main().
My code so far:
#include "stdafx.h"
#include <string.h>
#include <math.h>
typedef struct { // Custom data type for holding player information
char name[30]; // Name of Player
int overs, // No. of overs
maidens, // No. of Maidens
runs, // No. of runs scored
wickets; // No. of wickets scored
} member_t;
/* Function Prototypes */
void get_names(member_t allplayers[], FILE *input);
/* Function: To get names from file and place them in allplayers[] array */
void get_names(member_t allplayers[], FILE *input)
{
member_t current_player; // Current player being read from file
int input_status; // Status value returned by fscanf
int i = 0;
input_status = fscanf(input, "%s", ¤t_player.name); /////ISSUE HERE??
while (input_status != -1)
{
strcpy(allplayers[i].name, current_player.name);
allplayers[i].overs = 0;
allplayers[i].maidens = 0;
allplayers[i].runs = 0;
allplayers[i].wickets = 0;
input_status = fscanf(input, "%s", ¤t_player.name);
i += 1;
}
}
/* Main Function */
int
main(void)
{
FILE *fileinput_a; // Pointer to file input2a.dat for names
int i;
member_t allplayers[15];
fileinput_a = fopen("F:\\input2a.dat", "r"); // Opens file for reading
if (!fileinput_a) // Checks to see if file has any data
printf("File open error - File is empty"); // Empty file error
get_names(&allplayers[15], fileinput_a); // Send array as an output, and file pointer as input
for (i = 0; i < 15; i++)
{
printf("%10s ", allplayers[i].name);
printf("%d ", allplayers[i].overs);
printf("%d ", allplayers[i].maidens);
printf("%d ", allplayers[i].runs);
printf("%d\n", allplayers[i].wickets);
}
fclose(fileinput_a);
return(0);
}
Visual Studio 2013 doesn't seem to have an issue with the code, however once it gets up to the marked fscanf function, it throws an Access Violation at me when debugging.
return(1);after (and braces around) after theprintf("File open error...\n");statement.member_tone beyond the end of the array to your function.&allplayers[0]or justallplayerswould be OK.