-5

I am writing a program that creates a new data file that will take the numbers from the first file that are greater than 60 and save them to a new file.

I have began with my code but for some reason it is not saving the numbers greater than 60. I am new to programming, still learning so any help will be very much appreciated. What am I doing wrong?

#include <stdio.h>
main()
{
int y;
FILE *DATA;
DATA = fopen("RN.txt","r");
    fscanf(DATA, &y);
if (y > 60)
{
    DATA = fopen("RN.txt","w");
    fprintf(DATA, y, "");
}
printf("Finished saving file RN.txt \n");
return 0;
}
iBug
  • 35,554
  • 7
  • 89
  • 134
  • 3
    What does this have to do with Java? If you're tagging it a Java question just to bring attention to the question, it worked, but understand that some of that attention may be negative attention. – Hovercraft Full Of Eels Nov 27 '17 at 02:23
  • 3
    Well for starters, you need a loop of some sorts to read each line. SO is not a tutorial site. Sorry. See [here](https://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list) for C programming books. – OldProgrammer Nov 27 '17 at 02:26
  • 1
    A new file generally has a new name. You probably want to open it outside of whatever loop you have where you check for `>60` and either write or skip the number, and you're gonna need that loop. – Retired Ninja Nov 27 '17 at 02:31
  • Tagging [tag:c], [tag:c++11] and [tag:java] at the same time is very interesting. You can continue tagging like that if you want downvotes. – iBug Nov 27 '17 at 02:59

1 Answers1

1

There are several severe problems in your code.

My suggestions are as below:

  1. Compile your program (preferrably with -Wall, enabling all warnings). You'll be getting a bunch of errors and warnings. Fix them carefully, one-by-one.

  2. Learn How to debug small programs?

  3. Throw what you have into the bin and read one of the good C books. Then restart from scratch.


A few insights:

  1. You're using fscanf() and fprintf() wrongly:

    fscanf(DATA, "%d", &y);
    fprintf(DATA, "%d", y);
    
  2. Opening the same file with two different handles to read and write at the same time will run yourself into troubles, very quickly. Close after reading or writing, or use another file for writing

    fclose(DATA);
    

    OR

    FILE *OUT = fopen("RN.out.txt", "w");
    
  3. To repeat a specific process, you need a loop:

    while (fscanf(DATA, "%d", &y) > 0) {
        // process here
    }
    
iBug
  • 35,554
  • 7
  • 89
  • 134