I'm writing a program for an ATM. My .txt file is an account balance amount (in this case, 1500.00). How do I read in the .txt file, edit the account balance, and then save it to the file?
For example, if I were to ask a user to enter a deposit an amount of 300.00, I want to be able to add that 300.00 to the existing 1500.00 in the file, and then overwrite the 1500.00 with the total amount of 1800.00.
This is what I have so far.
float deposit;
float var;
printf("Current account balance:");
if ( (file_account = fopen ("account.txt", "r")) == NULL)
{
printf ("Error finding account balance.\n");
return;
}
while ( (fscanf (file_account, "%c", &var)) != EOF)
{
printf ("%c", var);
}
printf ("\n");
fclose (file_account);
for (deposit=0; deposit>0; deposit++)
{
if (deposit > 0)
{
printf ("Enter amount to deposit:");
scanf ("%f", &deposit);
//file_account + deposit;
fprintf (file_account, "Your new account balance is: %f", deposit);
}
else
{
printf ("Amount must be 0 or more.");
}
fclose (file_account);
}
You should use a File pointer to open & read the file, modify the contents according to your will and write back to file.
For example:
File *fp; // creates a pointer to a file
fp = fopen(filename,"r+"); //opens file with read-write permissions
if(fp!=NULL) {
fscanf(fp,"%d",&var); //read contents of file
}
fprintf(fp,"%d",var); //write contents to file
fclose(fp); //close the file after you are done
You need a few steps here:
int triedCreating = 0;
OPEN:
FILE *filePtr = fopen("test.txt", "r+");
if (!filePtr)
{
// try to create the file
if (!triedCreating)
{
triedCreating = 1;
fclose(fopen("test.txt", "w"));
goto OPEN;
}
fprintf(stderr, "Error opening file %i. Message: %s", errno, strerror(errno));
exit(EXIT_FAILURE);
}
// scan for the float
float value = 0.0f;
fscanf(filePtr, "%f", &value);
printf("current value: %f\nvalue to add: ", value);
// add the new value
float add = 0.0f;
scanf("%f", &add);
value += add;
// write the new value
fseek(filePtr, 0, SEEK_SET);
fprintf(filePtr, "%f", value);
fclose(filePtr);
You may wish to have different formatting for your printf()'s so that it looks nicer when read into a normal text editor.
you can read and edit a file with the help of basic FILE I/O(Input/ output) function in C i an simple manner like for example,writing to a file if it exist and if doesn't create a file with a name and then write to it.
A basic tutorial can be found at
http://www.tutorialspoint.com/cprogramming/c_file_io.htm
Now if you are talking about the complex .txt file having a lot of content in it and then you need to find a particular word and change it, i find it a bit difficult rather possible in Linux where you can call a script to read a file , edit it using SED,( stream editor for filtering and transforming text).You can find tutorials for it at below links
http://www.panix.com/~elflord/unix/sed.html
Related
I've used a ".txt" extension while reading and writing the file, also the file mode is corresponding to that of "text" type of file. The program runs fine, but instead of storing an ASCII character in the file, it is storing binary characters. I need some assistance here. Thank you.
int main(void)
{
FILE *fp;
int n2, n1;
printf("ENTER A NUMBER: ");
scanf("%d", &n1);
fp = fopen("hello.txt", "w");
if (fp == NULL)
{
printf("ERROR");
exit(1);
}
fprintf(fp, "%d", n1);
//fclose(fp);
//rewind(fp);
fp = fopen("hello.txt", "r");
if (fp == NULL)
{
printf("ERROR");
exit(1);
}
//n2 = getw(fp);
fscanf(fp, "%d", n1);
printf("%d", n1);
fclose(fp);
}
If you are going to close and reopen the file you don't need rewind. Or you can open the file to read and write, and then you can use rewind. Both work, here is a sample of the latter:
int main(void)
{
FILE *fp;
int n2, n1;
printf("ENTER A NUMBER: ");
if (scanf("%d", &n1) == 1) // checking if the input was correctly parsed
{
fp = fopen("hello.txt", "w+"); // open to read and write
if (fp == NULL)
{
printf("ERROR");
exit(1);
}
putw(n1, fp); // write to the file
rewind(fp); // go back to the beginning of the file
n2 = getw(fp); // get the data
printf("%d", n2);
fclose(fp);
}
else
{
puts("Bad input");
}
}
Live sample
There is still the matter of possible integer overflow when reading from stdin, if there is no requirement to guard against that, make sure to at least document the vulnerability, otherwise the advice is to use fgets to read input and strtol to convert the value.
You should send address of a variable in fscanf, like this:
fscanf(fp,"%d",&n1);
In this piece of code im getting value of row and column from the user.
But instead I wanted to know if i could extract these data from a file rather than manking the user input them.
Is there any way to do that?
Can you please help me guys im very new to his language, and im not even sure if we could do that
file format(5 is for rows and 4 is for columns):
5,4
printf("Please enter the number of rows that you would like to play on:");
scanf("%d", &row);
while (row < 3 || row >10)
{
fputs("Error, input a valid number: ", stderr);
scanf("%d", &row);
}
printf("please enter the number of columns that you would like to play on:");
scanf("%d", &col);
while (col < 3 || col > 10)
{
fputs("Error, input a valid number: ", stderr);
scanf("%d", &col);
}
You can access the contents of a file using a FILE pointer.
The address is set using fopen() where the first argument is a char* for the file name and the second is a char* for permissions (e.g. read, write, read and write, etc.).
If you can assume that the contents of the file are valid, you can open and read two numbers from a file as follows:
FILE *fp;
fp = fopen("filename", "r");
if(fscanf(fp, "%d,%d", &row, &col) != 2)) {
//handle error
printf("error\n");
}
fclose(fp);
Though I would still strongly recommend validating these anyways, as well as checking that the file contains all the required data before attempting to read it.
Yes, the fscanf function works much like the scanf function, but allows input from a FILE. The FILE must first be opened with fopen I recommend checking that the FILE is non-null and fscanf returns non-End-Of-File so you don't have undefined behaviour if the file is missing or invalid. See for example, the following code:
#include <stdio.h>
int main(){
FILE *fp;
int row, col;
fp = fopen("file.txt", "r"); /* open for "r"eading */
if (fp) {
if (fscanf(fp, "%d,%d", &row, &col)==2) {
printf("%d:%d", row, col );
}
}
fclose(fp);
return 0;
}
sure,the C standard library have a file system you can
Here a example on Writing and Reading to a file.
int main(void)
{
FILE *fp;
char buff[255];
fp = fopen("/myfolder/myfile.txt", "w+"); /*the w+ makes the file read and write*/
fprintf(fp, "This text is saved in the file\n");
fputs("This is another method\n", fp);
fscanf(fp, "%s", buff);
printf("%s\n", buff );
fgets(buff, 255, (FILE*)fp);
printf("%s\n", buff );
fclose(fp);
}
I'm trying to make a function that updates my csv text file.
The text file I have already has data inside it. I just want to change one of the values in one of the selected lines of data. I kind of confused on what to do here. When I try to print out the newInventory.numInstock it gives me the memory address. How can I get it to show me the text file values? I know I need to read the old file then copy what I need to a new file. Can someone help me out with this please.
My question is how do I get it to modify the numInStock? I want to be able to change that with this function.
/*here's my structure*/
struct inventory_s
{
int productNumber;
float mfrPrice;
float retailPrice;
int numInStock;// 4th column
char liveInv;
char productName[PRODUCTNAME_SZ +1];
};
/* My text file looks something like: */
1000,1.49,3.79,10,0,Fish Food
2000,0.29,1.59,100,1,AngelFish
2001,0.09,0.79,200,1,Guppy
5000,2.40,5.95,10,0,Dog Collar Large
6000,49.99,129.99,3,1,Dalmation Puppy
/*Here's my function so far*/
int updateStock(void)
{
struct inventory_s newInventory;
int productNumber;
char line[50];
FILE* originalFile = fopen("stuff.txt", "r"); //opens and reads file
FILE* NewFile = fopen("stuffCopy.txt", "w"); //opens and writes file
if(originalFile == NULL || NewFile == NULL)
{
printf("Could not open data file\n");
return -1;
}
printf(" Please enter the product number to modify:");
scanf(" %i", &productNumber);
printf("Current value is %i; please enter new value:", &newInventory.numInStock );
while(fgets(line, sizeof(line), originalFile) != NULL)
{
sscanf(line, "%d,%*f,%*f,%i", &newInventory.productNumber, &newInventory.mfrPrice, &newInventory.retailPrice, &newInventory.numInStock);
if (productNumber == newInventory.productNumber)
{
fputs(line, NewFile);
//fscanf(NewFile, "%s", &newInventory.productName);
printf(" %i",newInventory.numInStock);
}
}
fclose(originalFile);
fclose(NewFile);
// remove("stuff.txt");
//rename("stuffCopy.txt", "inventory.txt");
return 0;
}
So far I get it to print out the line that I'm trying to access. I need it to just access one of the values in the structure and show that one only. Then I need to change it to a new value from the user.
fix like this ( it will be your help.)
printf("Please enter the product number to modify:");
scanf("%i", &productNumber);
while(fgets(line, sizeof(line), originalFile) != NULL)
{
sscanf(line, "%i", &newInventory.productNumber);
if (productNumber == newInventory.productNumber)
{
sscanf(line, "%i,%f,%f,%i,%c,%[^\n]", &newInventory.productNumber,
&newInventory.mfrPrice,
&newInventory.retailPrice,
&newInventory.numInStock,
&newInventory.liveInv,
newInventory.productName);
printf("Current value is %i; please enter new value:", newInventory.numInStock );
scanf("%i", &newInventory.numInStock );
fprintf(NewFile, "%i,%f,%f,%i,%c,%s\n",newInventory.productNumber,
newInventory.mfrPrice,
newInventory.retailPrice,
newInventory.numInStock,
newInventory.liveInv,
newInventory.productName);
}
else
{
fputs(line, NewFile);
}
}
How can I do this?
I know opening a new file is something akin to this:
fpcon=fopen("konf_in","w");
printf("Whatever I want to input");
fclose(fpcon);
The output file only needs to be a simple .txt or .dat file
To write to a file, you need to call fprintf and pass your file pointer which is fpcon, see this example:
char name[20];
int number;
FILE *f;
f = fopen("/your_folder/sample.txt", "w");
if (f == NULL) {
printf("Error opening file!\n");
exit(1);
}
printf("\nNew contact name (max 19): ");
fgets(name, sizeof(name), stdin);
printf("New contact number: ");
scanf("%d", &number);
fprintf(f, "%s - %d\n", name, number);
fclose(f);
This page gives you further intel on how to handle file writes, appends, etc.
Just for clarification, the allowed modes for fopen are as follows:
r - open for reading
w - open for writing (file need not exist)
a - open for appending (file need not exist)
r+ - open for reading and writing, start at beginning
w+ - open for reading and writing (overwrite file)
a+ - open for reading and writing (append if file exists)
Trying to work with C I/O currently. I have a file that only holds integers and there is only one per line.. not commas, etc.. what is the best way to read them in:
//WHILE NOT EOF
// Read a number
// Add to collection
I am creating 2 files which is working fine.. but ultimately, I want to read them both in, join them into one collection, sort them and then print them out to a new file. There's no need for you to do all that for me, but please help with the above.. here is my effort so far:
void simpleCopyInputToOutput(void);
void getSortSave(void);
int main()
{
//simpleCopyInputToOutput();
getSortSave();
system("PAUSE");
return 0;
}
void getSortSave(void)
{
FILE *fp1;
FILE *fp2;
FILE *fpMerged;
printf("Welcome. You need to input 2 sets of numbers.\n");
printf("Please input the first sequence. Press 0 to stop.\n");
if ((fp1 = fopen("C:\\seq1.txt", "w")) == NULL)
{
printf("Cannot open or create first file!\n");
exit(1);
}
int num;
int i = 1;
while (num != 0)
{
printf("Please input value # %d\n", i);
scanf("%d", &num);
if (num == 0)
{
break;
}
fprintf(fp1, "%d\n", num);
i++;
}
printf("Please input the second sequence. Press 0 to stop.\n");
if ((fp2 = fopen("C:\\seq2.txt", "w")) == NULL)
{
printf("Cannot open or create second file!\n");
exit(1);
}
num = -1;
i = 1;
while (num != 0)
{
printf("Please input value # %d\n", i);
scanf("%d", &num);
if (num == 0)
{
break;
}
fprintf(fp2, "%d\n", num);
i++;
}
fclose(fp1);
fclose(fp2);
if ((fp1 = fopen("C:\\seq1.txt", "r")) == NULL)
{
printf("Cannot open first file!\n");
exit(1);
}
//WHILE NOT EOF
// Read a number
// Add to collection
//TODO: merge ints from both files, sort and output to new file
}
I would suggest you use fgets:
char buffer[16];
while (fgets(buffer, sizeof(buffer), fp1))
{
long value = strtol(buffer, NULL, 10);
/* Use the value... */
}
/* fgets failed ro read, check why */
if (!feof(fp1))
printf("Error: %s\n", strerror(errno));
Edit: How to get the number of entries in the file: If you don't keep track of it any other way (like e.g. having the number of items being the first line), the only solution may be to read the file twice. Once to count the number of lines, and once to read the actual numbers. Use fseek or rewind after the counting to "rewind" the read pointer to the beginning of the file.
I would personally put the counting in a separate function, and also the actual reading. This way you don't have to duplicate code if you want to read from multiple files.
Your problem can be divided into three different parts: reading in two files, sorting the data, and writing the output into a file. I am assuming here that the two input files are not already sorted. If they were, the problem would be greatly simplified (google for mergesort if that is the case).
If you want to open a file for reading, you have to use "r" instead of "w" as file open mode flag. In your example code the read/write parts are somehow reversed from what you describe above. Then you should use fscanf to read formatted input from a FILE*. scanf(...) is just short for fscanf(stdin, ...). You can access the files in the following way:
FILE *fin1 = fopen("seq1.txt", "r");
FILE *fin2 = fopen("seq2.txt", "r");
FILE *fout = fopen("out.txt", "w");
if (fin1 && fin2 && fout) {
// Do whatever needs to be done with the files.
}
if (fout)
fclose(fout);
if (fin2)
fclose(fin2);
if (fin1)
fclose(fin1);
Using dynamic memory to store the integers is difficult. You need to use realloc to grow a buffer as you write more and more data into it, and finally use qsort to sort the data. Someone else can hopefully give more insight into that if needed.