首先,我承認我是新手(第一年編程,要溫柔!)。我會非常感謝幫助!我一直在試圖找到這個問題的答案,但是我對指針的理解以及它們與打開文件的關係有些灰暗。問題的發送文件指針到另一個函數(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