Good day.

I need help on a program that I'm working on.

It's supposed to take the strings in input.txt and put the odd numbered lines to odd.txt and the even ones to even.txt.

here's the code I have made so far...

#include<stdio.h>
#include<stdlib.h>
#define p printf
#define s scanf

int main (int argc, char *argv[])
{
    
  FILE *fptr1, *fptr2, *fptr3;
  
  int count = 0;
  char check[256];
  char temp[256];
  fptr1=fopen("input.txt", "r"); 
  fptr2=fopen("Odd.txt", "w");
  fptr3=fopen("Even.txt", "w");
  
  while (fgets(temp, sizeof(temp), fptr1) != NULL)
  {
    fscanf(fptr1, "%s", &check);
    if (check != "\n")
    {
              
      if (count==1)
      {
             fputs(check,fptr2);//put first line in odd.txt
            }
      
      else if(count%2==1)
      {
             fputs(check,fptr2);//odd
            }
       
      else 
      {
             fputs(check,fptr3);//even
            } 
    }
    count+=1;
  }

  fclose(fptr1);
  fclose(fptr2);
  fclose(fptr3);
  
  p("Finished processing the file...\n\n");
  system("PAUSE");
  return 0;
}

The problem is that the first line should be in Odd.txt since it's line # 1 but it doesn't show.

I hope you guys could help me. thank you in advance!

Codes inside the while loop contains lots of ERROR.
Do consider them...

Edited 6 Years Ago by biswajit_cs07: n/a

Please check the result of this action:

fptr1=fopen("input.txt", "r");

Edited 6 Years Ago by gerard4143: n/a

Please check the result of this action:

fptr1=fopen("input.txt", "r");

The line is supposed to read the contents of input.txt.

Is it wrong? I am new in programming in C.

Codes inside the while loop contains lots of ERROR.
Do consider them...

Thank you for replying. Please show me where it was wrong. I want to learn.

You should check each file opening like below:

if (!(fptr1 = fopen("input.txt", "r")))
	{
		fputs("could not open input.txt!\n", stderr);
		exit(EXIT_FAILURE);
	}

Plus your loop can be simplified...get rid of

fscanf(fptr1, "%s", &check);

Its not required for this to work.

Also comments should be
/*comments are here*/
not
//comments are here

Edited 6 Years Ago by gerard4143: n/a

You do not need the fscanf function. At the point when end of the file is reached, the code will not enter the while loop. Consequently you can do away with the if on line 21
Also you instead of incrementing the count by 1 and then using the mod operation, another way could be to toggle the count values between 0 and 1 using if conditions

Edited 6 Years Ago by abhimanipal: n/a

This article has been dead for over six months. Start a new discussion instead.