[英]how to read from a file into array in c programming
我有一个名为Players.txt的文件,其中包含
Del Piero | 3 |意大利|尤文图斯罗纳尔多| 0 |葡萄牙|真实的Madrit
我想将每个病房读成一个分开的数组,就像数组播放器一样
players[NUM_PLAYERS][NAME_LENGTH]={ Del Piero,Ronaldo}
等其他数组,
我知道它需要使用一个名为fgets的函数和一些字符串函数。
这是我尝试过的; 我的问题是:我的问题是否有其他方法,比如使用一些不同的程序或字符串程序? 以及如何从该文件中获取目标数并将其存储到文件中
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <stddef.h>
#include <ctype.h>
#define NUM_PLAYERS 20
#define NAME_LENGTH 100
#define COUNTRY_NAME 20
int main (void)
{
FILE *Players;
char player_name [NUM_PLAYERS][NAME_LENGTH] = {0};
char team_name[NUM_PLAYERS][NAME_LENGTH] = {0};
char country_name[NUM_PLAYERS][COUNTRY_NAME] = {0};
char temp_buffer[NAME_LENGTH]={0};
int goals_scored[NUM_PLAYERS] = {0};
char *ptr1,*ptr2,*ptr3;
int i;
Players = fopen("Players.txt", "r");
if (Players == NULL)
{
printf("File not found.\n");
}
else
{
i=0;
while ((fgets(temp_buffer,sizeof(temp_buffer), Players) != NULL) && i < NUM_PLAYERS)
{
ptr1 = strchr(temp_buffer, '|');
strncpy(player_name[i], temp_buffer, ptr1 - temp_buffer);
printf("the name of the player is %s\n.", player_name[i]);
i ++;
}
}
fclose(Players);
return 0;
}
您可以尝试使用fscanf,而不是fgets + strchr。 然后你将获得更简单的代码和更安全(现在你的代码很容易溢出缓冲区,结果不可预测)。
if (fscanf(Players, " %*[^|]|%d|%*[^|]|%*s",
NAME_LENGTH-1, player_name[i],
goals_scored + i,
NAME_LENGTH-1, team_name[i],
NAME_LENGTH-1, country_name[i]) == 4) {
...
}
注意:该模式非常特定于您的数据格式,并且从您的问题中我不清楚country_name的分隔符(如果有)。 然后最后一个字符串模式是通常的%s
,它在第一个space
处停止
我建议使用fscanf
而不是在代码中使用fgets
。
有关详细的fscanf参考和使用文档,请参阅: http : //www.cplusplus.com/reference/cstdio/fscanf/
我建议使用mmapping:这样你就可以直接将文件的全部内容放到可寻址的内存中,这样你就可以随意查看数据了。
作为额外的好处,如果在调用mmap()时指定MAP_PRIVATE,则可以简单地将其剪切为单个字符串(用空字节替换“|”和“字符”)而不修改文件。 这样可以节省复制字符串的必要性。 其余的是在数据中构建索引结构的简单问题。
这是我使用的骨架:
const char* mmapInputFile(const char* path, int kernelAdvice, off_t* outLength) {
//Open the file.
int file = open(path, O_RDONLY);
if(file == -1) /* error handling */;
*outLength = lseek(file, 0, SEEK_END); //Get its size.
//Map its contents into memory.
const char* contents = (const char*)mmap(NULL, *outLength, PROT_READ, MAP_PRIVATE, file, 0);
if((intmax_t)contents == -1) /* error handling */;
if(madvise((void*)contents, *outLength, kernelAdvice)) /* error handling */;
//Cleanup.
if(close(file)) /* error handling */;
return contents;
}
请注意,在映射存在时不必保持文件打开。
从性能上讲,这可能是您可以实现的最佳目标,因为整个过程可以在不制作单个数据副本的情况下进行,从而节省了CPU时间和内存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.