简体   繁体   English

如何在c编程中从文件读取数组

[英]how to read from a file into array in c programming

I have a file called Players.txt which contains 我有一个名为Players.txt的文件,其中包含

Del Piero|3|Italy|Juventus Ronaldo|0|Portugal|Real Madrit Del Piero | 3 |意大利|尤文图斯罗纳尔多| 0 |葡萄牙|真实的Madrit

I want to read each ward into a separated array, like array players to contain 我想将每个病房读成一个分开的数组,就像数组播放器一样
players[NUM_PLAYERS][NAME_LENGTH]={ Del Piero,Ronaldo}
and so on with the other arrays, 等其他数组,

I know that it need to use a function called fgets and some string functions. 我知道它需要使用一个名为fgets的函数和一些字符串函数。

here is what i tried; 这是我尝试过的; My questions are : Is there any other approach to my problem, like to use some different programs, or string programs? 我的问题是:我的问题是否有其他方法,比如使用一些不同的程序或字符串程序? And how to get the number of goals form this file and store them into the file 以及如何从该文件中获取目标数并将其存储到文件中

#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;
}

You could try to use fscanf, instead of fgets+strchr. 您可以尝试使用fscanf,而不是fgets + strchr。 Then you will gain simpler code and more safeness (now your code will easily overflow the buffer, with unpredictable results). 然后你将获得更简单的代码和更安全(现在你的代码很容易溢出缓冲区,结果不可预测)。

 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) {
   ...
 }

note: the pattern is very specific to your data format, and from your question isn't clear to me what delimiter (if any) there is for country_name. 注意:该模式非常特定于您的数据格式,并且从您的问题中我不清楚country_name的分隔符(如果有)。 Then the last string pattern is the usual %s , that stops at first space 然后最后一个字符串模式是通常的%s ,它在第一个space处停止

I suggest using fscanf instead of using fgets in your code. 我建议使用fscanf而不是在代码中使用fgets

For detailed fscanf reference and usage doc, see: http://www.cplusplus.com/reference/cstdio/fscanf/ 有关详细的fscanf参考和使用文档,请参阅: http//www.cplusplus.com/reference/cstdio/fscanf/

I would recommend mmapping: That way you get the entire contents of the file directly into addressable memory, allowing you to examine the data at your leisure. 我建议使用mmapping:这样你就可以直接将文件的全部内容放到可寻址的内存中,这样你就可以随意查看数据了。

As an added bonus, you can simply cut it into individual strings (replacing the '|' and ' ' chars with null bytes) without modifying the file, if you specify MAP_PRIVATE in the call to mmap(). 作为额外的好处,如果在调用mmap()时指定MAP_PRIVATE,则可以简单地将其剪切为单个字符串(用空字节替换“|”和“字符”)而不修改文件。 This saves you the necessity to copy the strings. 这样可以节省复制字符串的必要性。 The rest is a simple matter of building an index structure into the data. 其余的是在数据中构建索引结构的简单问题。

This is the skeleton of what I use: 这是我使用的骨架:

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;
}

Note that it is not necessary to keep the file open while the mapping exists. 请注意,在映射存在时不必保持文件打开。

Performancewise this is probably the best you can achieve, because the entire process can happen without making a single copy of the data, which saves both CPU time and memory. 从性能上讲,这可能是您可以实现的最佳目标,因为整个过程可以在不制作单个数据副本的情况下进行,从而节省了CPU时间和内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在c编程中读取文本文件到数组结构的数据? - How to read and data from text file to array structure in c programming? C 编程:从文件中读取数字行并将其存储在数组中 - C programming: Read lines of numbers from a file and store it in an array 如何从.pgm文件中读取像素值并将其复制到数组中。 c编程 - How to read in pixel values from .pgm file and copy it into an array. c-programming 在C编程中,如何从文本文件中读取数据数组? - How can I read an array of data from a text file in my code in C programming? 读取文本文件并在C编程中存储在数组中 - read text file and store in array in c programming C编程:从文件读取并在屏幕上打印 - C Programming: Read from file and print on screen C编程:从文本文件中逐行读取(双精度)数字到2D数组 - C programming: Read (double) numbers from text file, line by line to a 2D array C编程,从文件读取并加载到数组中 - C programming, reading from a file and loading into an array 如何读取文本文件并将其存储在 C 编程中的数组中(以逗号分隔的值)? - How do I read a text file and store it in an array in C programming (values seperated by a comma)? 我试图打开 a.csv 文件并在 C 编程中将其作为数组中的字符串读取 - Im trying to open a .csv file and read it as strings in an array in C programming
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM