The following is my C code for file operations. I have to extract both of them into one rar file. They work on desktop but in rar the second code creates an empty txt. How can I make them work in rar file?
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp;
int number[100];
fp = fopen("numbers.txt", "w");
for (int i = 0; i < 100; i++) {
number[i] = rand() % 1000;
fprintf(fp, "%d\n", number[i]);
}
fclose(fp);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp;
FILE *fp1;
int number, count;
fp = fopen("numbers.txt", "r");
fp1 = fopen("numbers2.txt", "w");
while (!feof(fp)) {
count = 0;
fscanf(fp, "%d", &number);
for (int i = 2; i < number / 2; i++) {
if (number % i == 0) {
count++;
}
}
if (count == 0 && number >= 2) {
fprintf(fp1, "%d\n", number);
}
}
fclose(fp);
fclose(fp1);
return 0;
}
I created a text file that contained random 100 numbers in the first code and exported the prime ones to another text file in the second code.
In order to deal with files stored in an archive, the simplest method is to use the
systemfunction:when you are done creating the numbers.txt file, add the file to the archive with
system("rar a archive.rar numbers.txt"), then remove the file withremove("numbers.txt")to extract the file from the archive, use
system("rar e archive.rar numbers.txt")Regarding your code:
do not use
feof()to test for end of file, check the return value offscanf()instead.always check for
fopenfailuresand report meaningful messages.Here are modified versions:
and