DoeCodeMan DoeCodeMan -4 years ago 35
C Question

Trying to count the lines of text that is printed when reading a file using C programming language

I got a question from my Lecture I am in my first year and I can't solve this question

The Question is trying to ask me to create a program that read the text in a text file and output it in the console and count the lines being printed and see it on the console with outputted text?

Here is the pdf link for the actual question.
https://drive.google.com/file/d/0B0jqSF8uVDH3MHE3S2FhaHhWMXM/view

Here is the link to text file I am reading and outputting in the console.

https://drive.google.com/file/d/0B0jqSF8uVDH3WFBsdExaLXY4RDA/view

Here is the code I made and there is a error i have to removing the actually text output to make it which I don't want to do that.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
int current = 0;
FILE* p_file = 0;

char name[100];

printf("what file\n");
scanf("%s", &name);

p_file = fopen(name, "r");

current = fgetc(p_file);

int count = 0;

while (EOF != current)
{
count = count + 1;

printf("%d: ", count);
printf("%c", current);

current = fgetc(p_file);

}
fclose(p_file);

return 0;
}


Please any read the question and see if you can help

I am using Microsoft Visual Studio 2013?

Answer Source

This could work for you.

#define _CRT_SECURE_NO_WARNINGS 
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    FILE* p_file = 0;
    char name[100];
    char st[100];

    printf("what file\n");
    scanf("%s", name);

    p_file = fopen(name, "r");

    int count = 0;

    while (fgets(st, sizeof st, p_file) != NULL)
    {
        count = count + 1;

        printf("%d:  ", count);
        printf("%s", st);
    }
    fclose(p_file);

    return 0;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download