简体   繁体   English

将文件加载到C中的2D char数组中

[英]Load file into 2D char Array in C

I have a text file with 25 lines, each with 34 characters on. 我有一个包含25行的文本文件,每行包含34个字符。

In C how is it possible to load these characters and store them into a 2D array? 在C中,如何加载这些字符并将它们存储到2D数组中?

If the first three lines of the file are such: 如果文件的前三行是这样的:

bamaaaaaaaacxxxxxxxxxxbaaaaaaaamac
jzjzzzzzzzzdaaaaaaaaaaezzzzzzzzjzj
jzjzbaaczgzzzzzzzzzzzzzzgzbaaczjzj

...and so on

I require the array to be stored as if it was defined like this: 我要求存储数组,就好像它是这样定义的:

char* data[] = {
            "baaaaaaaaaaaaaacxxbaaaaaaaaaaaaaac",
            "jzzzzzzzzzzzzzzjxxjzzzzzzzzzzzzzzj",
            "jzbaaaaaaaaaaaaexxdaaaaaaaaaaaaczj",
...and so on

Hopefully this makes some sense! 希望这有点道理! It is important that the type of data is char data[][] as it is used in that format in the rest of my project and cannot be changed. 重要的是data类型是char data[][]因为它在我项目的其余部分以该格式使用,并且无法更改。

I have done the basic begining of the File IO 我已经完成了文件IO的基本开始

FILE  *infp;

printf("Opening file\n");

if((infp = fopen("file.txt", "r"))== NULL) {
    printf("\nERROR : Unable to open input file\n");
    SetExitWithCode( 999 );
    }else{
            //code here
            }

Can anyone help? 有人可以帮忙吗?

So, you want your array to look like this: 所以,你希望你的数组看起来像这样:

char data[25][35] //There is an extra 1 character per line to hold the null terminator character

Then simply read the whole file into that array 然后只需将整个文件读入该数组即可

fread(data, 1, sizeof(data), infp);

And finally, replace the new line character in on each line with a terminator 最后,用终结符替换每一行中的新行字符

for (int i = 0; i < 25; ++i) {
    data[i][34] = 0;
}

This is the easiest solution to the problem, but it is also a bad way of doing it. 这是解决问题的最简单方法,但这也是一种不好的方法。 It does not validate that the data is in the correct format, and everything is hard coded. 它不会验证数据格式是否正确,并且所有内容都是硬编码的。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM