user3743206
user3743206

Reputation: 19

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. 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). What functions can I used to read and store this text to a single char array?

Upvotes: 0

Views: 2374

Answers (2)

lost_in_the_source
lost_in_the_source

Reputation: 11237

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.

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 */

Upvotes: 1

DigitalNinja
DigitalNinja

Reputation: 1098

You could do something like this:

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

Upvotes: 0

Related Questions