I am trying to write a program that edits a text file containing the expenses of a user on codeblock.
stage one: there is a file name "abc.txt". It states the current amount and the expenditures per date. Using a loop, I copy "abc.txt" to another file, "test.txt".
stage two: with another loop I request the user to add a new date and new amount that will either be subtracted or added to the total amount.
stage three: I close both files and copy the "test.txt" file (which contains all the updated info) to the original abc.txt" file using another loop.
The problem is in the last stage; when copying the text, whitespace is not preserved.
If you want to use my code you should have 2 text files name "abc.txt" and "test.txt". leave the "test" file blank and in the "abc" file write this:
[0] Total amount: 79179 [1]
[1]
[1]
[1]
[0] Date: 1.1.19 [1]
[0] Sub: 10000 70000 [1]
[1]
[0] Date: 2.1.19 [1]
[0] Add: 10000 80000 [1]
[1]
[0] Date: 3.1.19 [1]
[0] Sub: 499 79501 [1]
[1]
[0] Date: 4.1.19 [1]
[0] Sub: 322 79179 [1]
[1]
And then run this code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE * filepointer;
filepointer=fopen("abc.txt","r");
char name[100];
char name1[1000];
int num;
int old_amount;
char date[20];
int flag=0;
int amount;
char action[10];
int tit;
FILE *test;
test=fopen("test.txt","w");
fscanf(filepointer,"%s %s %s %d", &name, &name, &name, &amount );
printf("The total amount: %d\n",amount);
while(!feof(filepointer))
{
fscanf(filepointer,"%s",name );
if(strcmp(name,"[1]")==0)
{
printf("\n");
fprintf(test,"[1]\n");
fscanf(filepointer,"%s ",name );
}
printf("%s ",name);
fprintf(test,name);
fprintf(test," ");
}
printf("Enter date: ");
scanf("%s",&date);
printf("date: %s\n ",date);
fprintf(test,"\n[0] Date: ");
fprintf(test,date);
fprintf(test," [1]\n");
while(flag==0)
{
fflush(stdin);
printf("What is th amount: ");
scanf("%d",&num);
printf("[0] %d\nstate action [S] [A]: ",num);
scanf("%s",&action);
if(strcmp(action,"a")==0 || strcmp(action,"A")==0)
{
fprintf(test,"\n[0] Add: %d ",num);
amount=amount+num;
fprintf(test,"%d [1]\n",amount);
printf("OK");
}
if(strcmp(action,"s")==0 || strcmp(action,"S")==0)
{
fprintf(test,"\n[0] Sub: %d ",num);
amount=amount-num;
fprintf(test,"%d [1]\n",amount);
printf("OK");
}
printf("\nDo you wish to add another value?[Y] [N]\n");
scanf("%s",&action);
if(strcmp(action,"n")==0 || strcmp(action,"N")==0)
{
flag=1;
}
}
fclose(test);
fclose(filepointer);
FILE * text;
text=fopen("test.txt","r");
FILE *abc;
abc=fopen("abc.txt","w");
fprintf(abc,"\n[0] Total amount: %d [1]\n",amount);
while(!feof(text))
{
fscanf(text,"%s",&name1 );
if(strcmp(name1,"[1]")==0)
{
//printf(" GOT IT \n");
fprintf(abc,"[1]\n");
fscanf(text,"%s ",&name1 );
}
printf("%s ",name1);
fprintf(abc,"%s ",name1);
fprintf(abc," ");
}
return 0;
}
When I run it in a project file it works fine, but when I run in as an application it causes trouble... any ideas?