This program is intended to read a .txt file to get a set of numbers, and write to another two .txt files called even and odd as follows:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int i=0,even,odd;
int number[i];
// check to make sure that all the file names are entered
if (argc != 3) {
printf("Usage: executable in_file output_file\n");
exit(0);
}
FILE *dog = fopen(argv[1], "r");
FILE *feven= fopen(argv[2], "w");
FILE *fodd= fopen (argv[3], "w");
// check whether the file has been opened successfully
if (dog == NULL)
{ printf("File %s cannot open!\n", argv[1]);
exit(0);
}
{ if
(i%2!=1)
i++;}
fprintf(feven, "%d", even);
fscanf(dog, "%d", &number[i]);
else {
i%2==1;
i++;}
fprintf(fodd, "%d", odd);
fscanf(dog, "%d", &number[i]);
fclose(feven);
fclose(fodd);
}
The { appear after the if() condition. And } should come after fscanf(dog, "%d", &number[i]);
if(i%2!=1){
i++;
fprintf(feven, "%d", even);
fscanf(dog, "%d", &number[i]);
}else {
i%2==1;
i++;
}
first
int i=0,even,odd;
int number[i];
means the length of Array number is 0.
you should write
if (argc != 3) {
printf("Usage: executable in_file output_file\n");
exit(0);
}
FILE *dog = fopen(argv[1], "r");
FILE *feven= fopen(argv[2], "w");
FILE *fodd= fopen (argv[3], "w");
int num;
while (fscanf(dog, "%d", &num) != EOF)
{
if(num % 2 == 0)
{
fprintf(feven, "%d", num);
}else
{
fprintf(fodd, "%d", num);
}
}
fclose(feven);
fclose(fodd);
fclose(dog);
{ if (i % 2 != 1)
i++;
}
fprintf(feven, "%d", even);
fscanf(dog, "%d", &number[i]);
else
{
i % 2 == 1;
i++;
}
Should be:
if (i % 2 != 1)
{
i++;
fprintf(feven, "%d", even);
fscanf(dog, "%d", &number[i]);
}
else
{
i % 2 == 1; //BTW this doesn't do anything.
i++;
}
EDIT: I've taken a few liberties so this might not be exactly your intent but it should be close enough. You need to work on a lot of small things which hopefully looking at the code will help with. Remember to understand what the functions do. And walk before you run.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int number;
// check to make sure that all the file names are entered
if (argc != 4)
{
printf("Usage: %s <inputfile> <even_outputfile> <odd_outputfile>\n", argv[0]);
exit(1);
}
FILE *dog = fopen(argv[1], "r");
FILE *feven = fopen(argv[2], "w");
FILE *fodd = fopen(argv[3], "w");
// check whether the file has been opened successfully
if (dog == NULL)
{
printf("File %s cannot open!\n", argv[1]);
exit(1);
}
if (feven == NULL)
{
printf("File %s cannot open!\n", argv[2]);
exit(1);
}
if (fodd == NULL)
{
printf("File %s cannot open!\n", argv[3]);
exit(1);
}
while (fscanf(dog, "%d", &number) == 1)
{
if (number % 2 == 0)
fprintf(feven, "%d ", number);
else
fprintf(fodd, "%d ", number);
}
fprintf(feven, "\n");
fprintf(fodd, "\n ");
fclose(dog);
fclose(feven);
fclose(fodd);
}
Related
I'm learning about file i/o in C language and I wrote this program that reads a file, and then for every even number found, it has to print * to the screen.
My problem is that my program keeps printing * forever.
I have tried different ways,some from this website, but I can't seem to understand how to read until end of a text file using EOF.
I want to learn how to read a text file until the end of the file please.
How do I read until the end of a text file? EOF in C.
int main(void)
{
int num;
FILE *ifp;
ifp = fopen("numbers.txt", "r" );
if(ifp == NULL)
{
exit(1);
}
do
{
fscanf(ifp, "%d", &num);
if(num%2 == 0)
{
printf("*\n");
}
} while(num != EOF);
fclose(ifp);
return 0;
}
you need to check the result of the scanf
do
{
int result;
result = fscanf(ifp, "%d", &num);
if(result == EOF) break;
if(result != 1)
{
printf("scanf error\n");
break;
}
if(num%2 == 0)
{
printf("*\n");
}
} while(1);
Instead, you should try while loop.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int num;
FILE *ifp;
ifp = fopen("numbers.txt", "r" );
if(ifp == NULL)
{
perror("Read");
exit(1);
}
while(fscanf(ifp, "%d ", &num) != EOF)
{
if(num % 2 != 0) // For every odd number.
{
printf("*\n");
}
}
fclose(ifp);
return 0;
}
Have you tried this:
while (!feof(ifp)) {
if (fscanf(ifp, "%d ", &num) > 0) {
if(num % 2 != 0) // For every odd number.
{
printf("*\n");
}
}
}
It's doing this because while(num != EOF) is testing whether int num, the number read from the file, is EOF, rather than whether the end of file has been reached.
To test whether the EOF flag has been set on FILE *ifp, use while(!feof(ifp)) instead.
The report file should contain the following:
1. Number of words
2. Number of uppercase letters
3. Number of lowercase letters
4. Number of digits
I have successfully read the file and counted the words letters and digits but i am having issues with writing the contents to the new file, any help would be appreciated.
#include <stdio.h>
#include <ctype.h>
#define SIZE 40
int main(void)
{
char ch, filename[SIZE];
int digits = 0;
int upper = 0;
int lower = 0;
int entered = 0;
int words = 0;
unsigned long count = 0;
FILE *fp;
printf("Please enter the filename to read: ");
gets(filename);
// "r" reads the file fopen opens the file
if ((fp = fopen(filename, "r")) == NULL)
{
printf("Cannot open the file, %s\n", filename);
}
else
{
puts("Successfully opened, now reading.\n");
while ((ch=getc(fp)) != EOF)
{
if (isalnum(ch))
{
if(!entered)
{
entered = 1;
words++;
}
}
else
{
if (entered)
{
entered = 0;
}
}
if (isupper(ch))
{
upper++;
}
else if (islower(ch))
{
lower++;
}
else if (isdigit(ch))
{
digits++;
}
}
}
fclose(fp); //make sure to close the file if you open one
char filename2 [SIZE];
FILE *fp2;
fprintf(stdout, "Please enter the file name to write in: ");
gets(filename2);
if ((fp2 = fopen("filename2", "w")) == NULL)
{
printf("Cannot create the file, %s\n", filename2);
}
else
{
fprintf(fp2, "The file \"%s\" has %lu Words.\n", filename, words);
fprintf(fp2, "The file \"%s\" has %lu Digits.\n", filename, digits);
fprintf(fp2, "The file \"%s\" has %lu upper case letters.\n", filename, upper);
fprintf(fp2, "The file \"%s\" has %lu lower case letters.\n", filename, lower);
}
fclose(fp2);
return 0;
}
Instead of
if ((fp2 = fopen("filename2", "w")) == NULL)
write
if ((fp2 = fopen(filename2, "w")) == NULL)
Then, kick yourself.
I am trying to write a code that simulates an Anti-Virus scan, it scans 5 specific files and then creates a file named AntiVirusLog.txt. In this file it writes the results, for example PSY.avi INFECTED. An infected file is a file that contains the string in the file youtubesign.
My problem is when I try to print in the results to the file AntiVirusLog.txt it does not print anything and leaves the file blank.
My code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<dirent.h>
#define BUZZ_SIZE 1024
int fast_scan(char *fname, char *str, FILE *fs);
int slow_scan(char *fname, char *str, FILE *fs);
int main(int argc, char *argv[])
{
char name[100];
char choice[5];
char buff[BUZZ_SIZE];
FILE *f7, *f2;
struct dirent *de;
DIR *dr = opendir(argv[1]);
if (dr == NULL) // opendir returns NULL if couldn't open directory
{
printf("Could not open current directory");
return 0;
}
f2 = fopen(argv[2], "rb");
f7 = fopen("AntiVirusLog.txt", "wt");
printf("Welcome to Amnon's Anti-Virus program\n which scan would you like to choose?:\n");
printf("Fast: check only the first and the last 20% of the file\n Slow: Checks the entire file\n");
printf("Enter fast for a fast scan and slow for a slow scan\n");
scanf("%s", choice);
if ((strcmp(choice, "slow"))==0)
{
while ((de = readdir(dr)) != NULL)
{
strcpy(name, argv[1]);
strcat(name, de->d_name);
if((fgets(buff, BUZZ_SIZE, f2)) != NULL)
{
slow_scan(name, buff, f7);
}
}
}
if ((strcmp(choice, "fast")) == 0)
{
while ((de = readdir(dr)) != NULL)
{
strcpy(name, argv[1]);
strcat(name, de->d_name);
if ((fgets(buff, BUZZ_SIZE, f2)) != NULL)
{
fast_scan(name, buff, f7);
}
}
}
printf("The scan was made successfuly, check the file AntiVirusLog.txt to see the results\n");
closedir(dr);
fclose(f2);
fclose(f7);
system("PAUSE");
return (0);
}
int slow_scan(char *fname, char *str, FILE *fs)
{
int findres = 0;
FILE *fp;
char temp[BUZZ_SIZE];
if ((fopen_s(&fp, fname, "rb")) != NULL)
{
return(-1);
}
while ((fgets(temp, BUZZ_SIZE, fp)) != NULL)
{
if ((strstr(temp, str)) != NULL)
{
fprintf(fs, "%s INFECTED\n", fname);
findres++;
}
}
if (findres==0)
{
fprintf(fs, "%s NOT INFECTED\n", fname);
}
fclose(fp);
return(0);
}
int fast_scan(char *fname, char *str, FILE *fs)
{
int findres=0;
int i, j, len, partlen;
FILE *fp;
if ((fopen_s(&fp, fname, "rb")) != NULL)
{
return(-1);
}
fseek(fp, 0, SEEK_END);
len = ftell(fp);
partlen = (len * 20) / 100;
char *temp=malloc(partlen);
while ((fgets(temp, BUZZ_SIZE, fp)) != NULL)
{
for (i = 0; i < partlen; i++)
{
if (temp[i]=str[i])
{
findres++;
}
if (temp[i] != str[i])
{
i = partlen + 1;
}
if (findres == partlen)
{
fprintf(fs, "%s INFECTED\n", fname);
i = partlen + 1;
}
}
for (j = len - partlen; j < len; j++)
{
if (temp[j] = str[j])
{
findres++;
}
if (temp[j] != str[j])
{
j = partlen + 1;
}
if (findres == partlen)
{
fprintf(fs, "%s INFECTED\n", fname);
j = partlen + 1;
}
}
}
if (findres!= partlen)
{
fprintf(fs, "%s NOT INFECTED\n", fname);
}
fclose(fp);
return(0);
}
There are primarily two major issues with your code
Point 1: In your code, for the series of calls like
search_sign(argv[1], buff, f7);
you're using buff uninitialized. The buff is then passed as the second parameter of search_sign(), (to be accepted as str) which is again used as the search string in strstr().
As buff is an automatic local variable, the initial content (value) is garbage (indeterminate) and hence , when used as the search key in strstr(), will invoke undefined behaviour.
Point 2: That said, as my previous comment, you should always be checking the success of fopen() call(s) before using the returned file pointer any further.
I have used some of the advices listen and found some fixes of my own and now it works perfectly! the updated code looks like this:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define BUZZ_SIZE 1024
int search_sign(char *fname, char *str, FILE *fs);
int main(int argc, char *argv[])
{
char buff[BUZZ_SIZE];
FILE *f,*f7;
f7 = fopen("AntiVirusLog.txt", "wt");
f = fopen(argv[1], "rb");
if ((fgets(buff, BUZZ_SIZE, f)) != NULL)
{
search_sign(argv[2], buff, f7);
search_sign(argv[3], buff, f7);
search_sign(argv[4], buff, f7);
search_sign(argv[5], buff, f7);
search_sign(argv[6], buff, f7);
}
printf("The scan was made successfuly, check the file AntiVirusLog.txt to see the results\n");
fclose(f);
fclose(f7);
system("PAUSE");
return (0);
}
int search_sign(char *fname, char *str, FILE *fs)
{
int findres = 0;
FILE *fp;
char temp[BUZZ_SIZE];
if ((fopen_s(&fp, fname, "rb")) != NULL)
{
return(-1);
}
while ((fgets(temp, BUZZ_SIZE, fp)) != NULL)
{
if ((strstr(temp, str)) != NULL)
{
fprintf(fs, "%s INFECTED\n", fname);
findres++;
}
}
if (findres==0)
{
fprintf(fs, "%s NOT INFECTED\n", fname);
}
fclose(fp);
return(0);
}
I'm starting to learn C, and currently programming a little text-based lottery-like game. But I need a way to store the value in the end of the game, so it can be kept for the next plays. I made a simpler code below that represents what I need. Please help.
#include <stdio.h>
int main() {
//TODO get "int saved" from save.txt
printf("Value saved: %d\n", saved);
printf("Add: ");
int add;
scanf("%d", &add);
int new = saved+add;
printf("New value: %d\n", new);
//TODO save "int new" to save.txt
}
save.txt:
100
Try this
FILE *file;
int saved;
int add;
file = fopen("saved.txt", "r");
if (file == NULL)
{
fprintf(stderr, "error opening `saved.txt'\n");
return -1;
}
if (fscanf(file, "%d", &saved) != 1)
{
fprintf(stderr, "file `saved.txt' corrupted\n");
fclose(file);
return -1;
}
fprintf(stdout, "please input an integer > ");
if (scanf("%d", &add) != 1)
{
fprintf(stderr, "invalid input\n");
fclose(file);
return -1;
}
fclose(file);
file = fopen("saved.txt", "w");
if (file != NULL)
{
fprintf(file, "%d\n", saved + add);
fclose(file);
}
I am using Code Blocks and I would like to delete a file using C. The file is used by two functions but not simultaneously.
This is the first function which uses the file:
double FileRead()
{
double n,cl,cd,result;
FILE *fd;
char filename[] = "save.txt";
char buff[5024];
if ((fd = fopen(filename, "r")) != NULL)
{
fseek(fd, 0, SEEK_SET);
while(!feof(fd))
{
memset(buff, 0x00, 5024);
fscanf(fd, "%[^\n]\n", buff);
}
sscanf(buff, "%lf %lf %lf",&n,&cl,&cd);
printf("cl: %1.5f cd: %1.5f\n",cl,cd);
result = (cl/cd);
printf("The CL/CD ratio is : %1.5f\n",result);
}
else
result = 0;
fclose(fd);
return result;
}
And this is the second function:
void evaluate(void) /*evaluate the population */
{
int mem;
int i;
double x[NVARS+1];
char buffer[101] = "save.txt";
FILE *controlpoints;
double y[NVARS] = {1.00000,0.92544,0.82351,0.78301,0.74004,0.50199,0.40422,0.31056, /*fixed values on x axis */
0.18549,0.14954,0.11702,0.06331,0.02581,0.01334,0.00509,0.00000,0.00052,0.00555,0.03324,
0.11345,0.33088,0.43678,0.60146,0.70751,0.8043,0.92047,0.98713,1.00000};
for(mem = 0; mem < POPSIZE; mem++)
{
controlpoints = fopen("controlpoints2.txt","w");
for(i = 0; i < NVARS; i++)
{
x[i+1] = population[mem].gene[i];
fprintf(controlpoints,"%1.5f\n%1.5f\n",y[i],x[i+1]);
printf("The value of population[%d].gene[%d] is %f\n",mem,i,population[mem].gene[i]);
}
fclose(controlpoints);
rbspline();
XfoilCall();
population[mem].fitness = FileRead();
}
remove(buffer);
if(remove(buffer) == 0)
printf("File %s deleted.\n", buffer);
else
fprintf(stderr, "Error deleting the file %s.\n", buffer);
}
All the time I am getting the message "Error deleting the file save.txt". Can you please check it out and tell me what am I doing wrong?
Your code in the second function contains:
remove(buffer);
if (remove(buffer) == 0)
printf("File %s deleted.\n", buffer);
else
fprintf(stderr, "Error deleting the file %s.\n", buffer);
You're removing the file twice and the second time it isn't there, so you report failure.
Fix: remove the unchecked remove(buffer) line.
Look at this part of the code
remove(buffer);
if(remove(buffer) == 0)
printf("File %s deleted.\n", buffer);
else
I think you want this
ret=remove(buffer);
if(ret==0)
printf("File %s deleted.\n", buffer);
else