简体   繁体   English

如何从文本文件中读取行并将其存储为char数组?

[英]How to read lines from a text file and store as char array?

I have an input text file with some instructions and, starting with line 7, several lines of text. 我有一个带有一些说明的输入文本文件,从第7行开始,有几行文本。 Something like this: 像这样:

hi gBroThuo oWdbmna eo mt ce oneain,nDustuh o n
Ade ds,bpopoonf  oneigno abro wmt  eIw
n,Yrtyt hlil t .s Ble a  meyboefr rtIhoyod
wla rimw yidehl. kes ,oyn L  af
fu;AcMadmdnae  nddmh ita behsctr rft iHdo"l,sie g"hu!,n eoaecMBt-
- h

I need to store the text to be stored in a char array (including the new line characters). 我需要将要存储的文本存储在char数组中(包括换行符)。 What functions can I used to read and store this text to a single char array? 我可以使用哪些函数来读取此文本并将其存储到单个char数组中?

char fileBuf[MAXFILE];
FILE *f;
int c;
size_t i;

if (f = fopen("filename", "r")) {
    for (i = 0; i < (MAXFILE - 1) && (c = getc(f)) != EOF; ++i)
        fileBuf[i] = c;
    fclose(f);
} else perror("Could not open file");

EDIT: you said you wanted to skip the first 7 lines. 编辑:您说您想跳过前7行。

int x;
char line[MAXLINE];
for (x = 0; x < 7; ++x)
    fgets(line, MAXLINE, f); /* skips first 7 lines, so now file pointer
                                will point to data after the 7 lines */

You could do something like this: 您可以执行以下操作:

int i = 0;
while(fscanf(inputFile, %c, &charArray[i])!=EOF)
   i++;

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

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