简体   繁体   中英

Reading input from file in C

Okay so I have a file of input that I calculate the amount of words and characters in each line with success. When I get to the end of the line using the code below it exits the loop and only reads in the first line. How do I move on to the next line of input to continue the program?

EDIT: I must parse each line separately so I cant use EOF

while( (c = getchar()) != '\n')

Change '\\n' to EOF . You're reading until the end of the line when you want to read until the end of the file (EOF is a macro in stdio.h which corresponds to the character at the end of a file).

Disclaimer: I make no claims about the security of the method.

'\\n' is the line feed (new line)-character, so the loop will terminate when the end of first line is reached. The end of the file is marked by an end-of-file (EOF)-characte. cstdio (or stdio.h), which contains the getchar()-function, has the EOF -constant defined, so just change the while-line to

while( (c = getchar()) != EOF)

From the man page: "reads the next character from stream and returns it as an unsigned char cast to an int, or EOF on end of file or error." EOF is a macro (often -1) for the return of this and related functions that indicates end of file. You want to check whether this is what you're getting back. Note that getc returns a signed int, but that valid values are unsigned chars cast to ints. What out if c is a signed char.

Well, the \\n character is actually a combination of two characters, two bytes: the 13th byte + the 10th byte. You could try something like,

int c2=getchar(),c1;
while(1)
{
  c1=c2;
  c2=getchar();
  if(c1==EOF)
    break;
  if(c1==(char)13 && c2==(char)10)
    break;

  /*use c1 as the input character*/
}

this should test if two input characters make the proper couplet (13,10)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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