Naresh
Naresh

Reputation: 657

File Handling in C

Sorry for asking very simple question.I'm new to coding.
Input txt file

5,3
001
110
111
110
001

I need to print the output as

U1: 001
U2: 110
U3: 111
U4: 110
U5: 001

Upto now I was able to print the contents with this:

  #include <stdio.h>
  void main() {
    FILE *fopen(), *fp;
    int c;

    fp = fopen("read.txt","r");
    c = getc(fp) ;

    while (c!= EOF) {
      putchar(c);
      c = getc(fp);
    }

    fclose(fp);
  }

Can Anybody tell how should I proceed?

Upvotes: 0

Views: 177

Answers (2)

Jerry Coffin
Jerry Coffin

Reputation: 490663

I would read the data a line at a time with fgets. When you have a complete line in a buffer, it'll be pretty easy to get fprintf to put in your line header with a format like "U%d: %s\n".

Upvotes: 0

pmg
pmg

Reputation: 108986

Most of your work is done inside the while loop.
But you're not doing enough work ...
a) you need to count lines
b) you need to print the "U#"

Suggestion: create a variable for the line counting business and rewrite your loop to consider it. Here's a few snippets

int linecount = 0;


printf("U%d: ", linecount)


if (c == '\n') linecount += 1;

Oh! You really shouldn't add the prototype for fopen yourself. It is already specified with #include <stdio.h>.

And well done for declaring c as int. Many people do the error of declaring it char which is incompatible with EOF and all the range of characters

Upvotes: 2

Related Questions