簡體   English   中英

如何在c編程中從文件讀取數組

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM