Open file and print user selected number of lines
I am getting compiler errors in my for loop and an illegal break within said for loop...Help?
Errors:
1>c:\users\robert\my programs\assignment 8_exercise 2\source.c(36) : error C2143: syntax error : missing ')' before ';'
1>c:\users\robert\my programs\assignment 8_exercise 2\source.c(36) : error C2059: syntax error : ')'
1>c:\users\robert\my programs\assignment 8_exercise 2\source.c(41) : error C2043: illegal break
Code:
#include <stdio.h>
#include <stdlib.h>
#define LINECOUNT 3;
#define SOURCE_FILE "C:/Users/Robert/Desktop/TestFile1.txt"
int main()
{
char c;
int lineCounter = 0;
FILE *file;
file = fopen(SOURCE_FILE, "r");
if(file==NULL)
{
printf("Error: can't open file.\n");
return 1;
}
else
{
printf("File opened successfully. Contents:\n\n");
for(lineCounter = 0; lineCounter <= LINECOUNT;;)
{
c = fgetc(file);
if(c = EOF)
{
break;
}
else if(c = '\n')
{
printf("%c", c);
lineCounter++;
}
else
{
printf("%c", c);
}
}
printf("\n\nNow closing file...\n");
fclose(file);
return 0;
}
}
Fixed the compiler errors, but no text prints...
I was hoping this would print the first three lines of text?
Here is my code:
Code:
#include <stdio.h>
#include <stdlib.h>
#define LINECOUNT 3
#define SOURCE_FILE "C:/Users/Robert/Desktop/TestFile1.txt"
int main()
{
char c;
int lineCounter = 0;
FILE *file;
file = fopen(SOURCE_FILE, "r");
if(file==NULL)
{
printf("Error: can't open file.\n");
return 1;
}
else
{
printf("File opened successfully. Contents:\n\n");
for(lineCounter = 0; lineCounter <= LINECOUNT;)
{
c = fgetc(file);
if(c = EOF)
{
break;
}
else if(c = '\n')
{
printf("%c", c);
lineCounter++;
}
else
{
printf("%c", c);
}
}
printf("\n\nNow closing file...\n");
fclose(file);
return 0;
}
}
Thank you, it works, I am trying to add one more feature...
I would like the program to wait for user to hit the newline (Enter key) after it prints the first 3 lines of text, if the enter key is hit the program will print three more lines of text, this process will continue for length of document. If any other key is hit before the newline, the program will terminate. Any ideas? Here is my code so far:
Code:
#include <stdio.h>
#include <stdlib.h>
#define LINECOUNT 3
#define SOURCE_FILE "C:/Users/Robert/Desktop/TestFile1.txt"
int main()
{
char c;
int lineCounter = 0;
FILE *file;
file = fopen(SOURCE_FILE, "r");
if(file==NULL)
{
printf("Error: can't open file.\n");
return 1;
}
else
{
printf("File opened successfully. Contents:\n\n");
for(lineCounter = 0; lineCounter < LINECOUNT; )
{
c = fgetc(file);
if(c == EOF)
{
break;
}
else if(c == '\n')
{
printf("%c", c);
lineCounter++;
}
else
{
printf("%c", c);
}
}
printf("\n\nNow closing file...\n");
fclose(file);
return 0;
}
}