首先,我承认我是新手(第一年编程,要温柔!)。我会非常感谢帮助!我一直在试图找到这个问题的答案,但是我对指针的理解以及它们与打开文件的关系有些灰暗。问题的发送文件指针到另一个函数(C编程)
说明:
我想从文件中读取一串的名字(如字符数组),并将它们存储在数组中。我之前有过这样的工作,但现在我想在名为get_names()的不同函数中填充名称,同时处理main()中打开的文件。
我迄今为止代码:
#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似乎并没有与代码中的问题,但是一旦进入到标记fscanf函数,它抛出一个访问冲突在我的时候调试。
get_names(allplayers [15],fileinput_a) ;你想在这里做什么,因为它确实看起来不正确。 – OldProgrammer 2014-10-03 01:30:31
还在缩进! 此外,我认为大括号是get_names()的近括号。前一个是关闭我的while循环。当我从我的程序中复制它时,它一定会被移动。 – Yoshi 2014-10-03 01:30:37
您测试文件指针,但您的打印语句不会以换行符结束,因此您可能看不到该消息,并且您肯定继续,因为它一切正常。它可能不是好的。在printf(“文件打开错误... \ n”);'语句之后添加一个'return(1);'后面(并且用大括号括起来)。 – 2014-10-03 01:31:50