C - Read/write int variable in .txt - c

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);
}

Related

Merging 2 text files on a new line

I'm creating a program to merge 2 text files in C (these 2 files must have already exist in the system)
#include <stdio.h>
#include <stdlib.h>
int main() {
char c;
char n1[10], n2[10];
FILE *f1, *f2, *f3;
printf("Please enter name of file input 1: ");
scanf("%s", n1);
f1 = fopen(n1, "r");
printf("Please enter name of file input 2: ");
scanf("%s", n2);
f2 = fopen(n2, "r");
f3 = fopen("question_bank.txt", "w");
if (f1 == NULL || f2 == NULL || f3 == NULL) {
printf("Error");
return 1;
}
while ((c = fgetc(f1)) != EOF) {
fputc(c, f3);
}
while ((c = fgetc(f2)) != EOF) {
fputc(c, f3);
}
fclose(f1);
fclose(f2);
fclose(f3);
return 0;
}
Everything is pretty ok but I realise that I need to enter the second file's content on a new line, not at the end of the first file's text. What change should I apply to my code?
If the first file does not end with a newline character, you should output one before copying the contents of the second file.
Note also that c must be defined as int.
Here is a modified version:
#include <errno.h>
#include <stdio.h>
#include <string.h>
int main() {
int c, last = 0;
char n1[80], n2[80];
FILE *f1, *f2, *f3;
printf("Please enter name of file input 1: ");
if (scanf("%79s", n1) != 1)
return 1;
printf("Please enter name of file input 2: ");
if (scanf("%79s", n2) != 1)
return 1;
f1 = fopen(n1, "r");
if (f1 == NULL) {
fprintf(stderr, "Cannot open %s: %s\n", n1, strerror(errno));
return 1;
}
f2 = fopen(n2, "r");
if (f2 == NULL) {
fprintf(stderr, "Cannot open %s: %s\n", n2, strerror(errno));
return 1;
}
f3 = fopen("question_bank.txt", "w");
if (f3 == NULL) {
fprintf(stderr, "Cannot open %s: %s\n", "question_bank.txt", strerror(errno));
return 1;
}
while ((c = fgetc(f1)) != EOF) {
last = c;
fputc(c, f3);
}
if (last != '\n') {
fputc('\n', f3);
}
while ((c = fgetc(f2)) != EOF) {
fputc(c, f3);
}
fclose(f1);
fclose(f2);
fclose(f3);
return 0;
}

Write a program that reads the contents of a text file and writes the number of words, upper/lowercase letters and digits into a separate file

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.

Search for keyword in textual file C

I'm having trouble reading a keyword from file that a user inputs to search for. The first part of the program asks for user input for naming the file. It then asks for sentence input. You can input sentences until you write "END". When you write "END", the appending of sentences to file should stop and the program should ask you for a keyword to search the sentences appended to the newly created textual file. I used 'gets' to ask for a word that will be searched for in the file. The program should find that word in a sentence and print back the whole sentence containing the keyword. The whole code looks like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char fileName[128];
printf("Input your filename (end with .txt):");
gets(fileName);
FILE *filePointer = NULL;
char text1[128];
char word1[128];
filePointer = fopen(fileName, "a");
if(filePointer == NULL)
{
printf("Cannot open file!");
exit(EXIT_FAILURE);
}
else{
printf("Input your sentence: ");
while (fgets(text1, 127, stdin) != NULL && strncmp(text1, "END\n", 5) != 0){
printf("Input your sentence: ");
fprintf(filePointer, "%s", text1);
}
int line_num = 1;
int find_result = 0;
char text2[128];
filePointer = fopen(fileName, "r");
printf("Input keyword you're looking for: ");
gets(word1);
while(fgets(text2, 127, filePointer) != NULL) {
if((strstr(text2, word1)) != NULL) {
printf("A match found on line: %d\n", line_num);
printf("\n%s\n", tekst2);
find_result++;
}
line_num++;
}
if(find_result == 0) {
printf("\nSorry, couldn't find a match.\n");
}
if(filePointer) {
fclose(filePointer);
}
return(0);
}
}
It all works, but the problem is somewhere here:
int line_num = 1;
int find_result = 0;
char text2[128];
filePointer = fopen(fileName, "r");
printf("Input keyword you're looking for: ");
gets(word1);
while(fgets(text2, 127, filePointer) != NULL) {
if((strstr(text2, rijec)) != NULL) {
printf("A match found on line: %d\n", line_num);
printf("\n%s\n", text2);
find_result++;
}
line_num++;
}
I'm new at C programming, so I'm not sure where the flaw is. I know it should work in theory. It doesn't return a result when it clearly should.
You need to fclose() the file after writing, before reopening to read.
if (fclose(filePointer) != 0)
{
fputs("The sky is falling.", stderr);
return 1;
}
filePointer = fopen(fileName, "r");

Cannot delete file in C

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

how to fix my error saying expected expression before 'else'

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);
}

Resources