Deleting a line of text in a text file by its context - c

I have a function for a pet store inventory program. So far, it will list the inventory, and add an item to the inventory. Now I'm trying to delete an item by its productNumber(first value store in csv text file). I changed my code around I just need a litte help with the condition. I need it to scanf the productNumber and delete the line by its product number.
QUESTION: how do I get the condition to look for the productNumber in the text file ,so I can delete that line in the text file.
I need some help please! I have a csv text file that is set up as the following structure:
struct inventory_s
{
int productNumber;
float mfrPrice;
float retailPrice;
int numInStock;
char liveInv;
char productName[PRODUCTNAME_SZ +1];
};
/*Originalfile I'm trying to copy and delete from looks 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
/*function looks like*/
int deleteProduct(void)
{
struct inventory_s newInventory;
char line[50];
//int del_line, temp = 1;
FILE* originalFile = fopen("inventory.txt", "r"); //opens and reads file
FILE* NewFile = fopen("inventoryCopy.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 delete:");
sscanf(line," %i", &newInventory.productNumber);
while(fgets(line, sizeof(line), originalFile) !=NULL)
{
if (!(&newInventory.productNumber))
{
fputs(line, NewFile);
}
}
fclose(originalFile);
fclose(NewFile);
return 0;
}
/*Input from user: 1000*/
/* What needs to happen in Newfile*/
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

fix like this
printf("Please enter the product number to delete:");
int productNumber;
scanf("%i", &productNumber);
while(fgets(line, sizeof(line), originalFile) != NULL)
{
sscanf(line, "%i", &newInventory.productNumber);
if (productNumber != newInventory.productNumber)
{
fputs(line, NewFile);
}
}

Related

How to make my program increase the price of the book (percent) depending on user inputs?

I've made a program that reads a file named "books.txt" and displays its contents. In the file, there is a price for each of the 4 books.
I'm not sure how to make my program increase the price of the book (percent) depending on user inputs; for example, the user is prompted to enter a number and that number (which is a percentage) is multiplied by the price of each book and gives the updated price.
How do I do it?
Here's my code:
int main() {
/* File pointer to hold reference to our file */
FILE * fPtr;
char buffer[BUFFER_SIZE];
int totalRead = 0;
/*
*/
fPtr = fopen("books.txt", "r");
if (fPtr == NULL) {
printf("Unable to open file.\n");
printf("Please check whether file exists and you have read privilege.\n");
exit(EXIT_FAILURE);
}
printf("File opened successfully. Reading file contents line by line. \n\n");
while (fgets(buffer, BUFFER_SIZE, fPtr) != NULL) {
totalRead = strlen(buffer);
/*
*/
buffer[totalRead - 1] = buffer[totalRead - 1] == '\n'
? '\0'
: buffer[totalRead - 1];
printf("%s\n", buffer);
}
fclose(fPtr);
return 0;
}
You can read the file and store all the book data in some array of struct such as
typedef struct {
int id;
char *title;
char *author;
int year;
float price;
}Book;
Then ask for the percentage to the user and re-write the file calculating the new price for each Book (price += percentage/100)
To re-write the file you need to open the file with "w permits. You can check for documentation here. Don't forget to close fPtr before opening the same file again with write permits

why i can not merge two file and store contents to another file in C

void mergeFile(){
//allocate memory
char * firFile = (char*) malloc(MAX_SIZE);
char * secFile = (char*) malloc(MAX_SIZE);
char * conFile = (char*) malloc(MAX_SIZE);
char * buffer = (char*) malloc(MAX_SIZE);
char ch;
// get name of first file
printf("Enter name of first file: ");
__fpurge(stdin);
gets(buffer);
strcpy(firFile, FOLDER);
strcat(firFile, buffer);
//get name of second file
printf("Enter name of second file: ");
__fpurge(stdin);
gets(buffer);
strcpy(secFile, FOLDER);
strcat(secFile, buffer);
//get name of file will store
printf("Enter name of file which will store contents of two files : ");
__fpurge(stdin);
gets(buffer);
strcpy(conFile, FOLDER);
strcat(conFile, buffer);
//open 3 file with 'r' and 'w' mode
FILE * firPtr = fopen(firFile,"r");
FILE * secPtr = fopen(secFile, "r");
FILE * conPtr = fopen(conFile, "w");
//check 3 file NULL or not
if (firPtr == NULL) {
printf("Can not open %s file\n", firFile);
remove(conFile);
} else if (secPtr == NULL) {
printf("Can not open %s file\n", secFile);
remove(conFile);
} else if (conPtr == NULL){
printf("Can not open %s file\n",conFile);
}else{
// write all character in first file to file will store
// MAY NOT WORK
while ((ch = fgetc(firPtr)) != EOF)
fprintf(conPtr, "%c", ch);
// write all character in second file to file will store
// MAY NOT WORK
while ((ch = fgetc(secPtr)) != EOF)
fprintf(conPtr, "%c", ch);
printf("Two file were merged into %s file successfully\n!",conFile);
}
//clear all
free(buffer);
free(firFile);
free(secFile);
free(conFile);
fclose(firPtr);
fclose(secPtr);
fclose(conPtr);
}
I use fget to get character from file and write to another file, I work well when i use two file, one for read and one for store, But when i try to merge two file to another file, this code didn't work, no things in side contains file. I run this code in Netbeans 8.2, can you give me mistake from this code, thanks so much!

Program to find specific word and then ouput the line of that word in a text file

So my problem is that I have a text file with names and services that they ordered. I need to search a file for a given name and then output a line on which that name is located. Here's my code, although it outputs the content of a line and not the actual line
printf("What is the customer's name\n");
scanf("%s", &name);
f = fopen("C:\\customer_info.txt", "r");
while (fgets(line, sizeof(line), f) != NULL)
{
if (strstr(line, name) != NULL)
{
printf("%s", line);
}
}
Try this way:
#include <stdio.h>
#include <string.h>
#define MAX 100
int main(void) {
char word_to_find[MAX], line[MAX];
FILE *fp = fopen("customer_info.txt", "r");
FILE *fp_write = fopen("customers_new_added.txt", "a");
unsigned short FLAG_FOUND = 0;
if (!fp) {
printf("Failed to open the file.\n");
return -1;
}
printf("Enter a customer name to find: ");
fgets(word_to_find, MAX, stdin);
while (fgets(line, sizeof(line), fp) != NULL) { // reading till NULL of File
if (strstr(line, word_to_find) != NULL) { // finding till NULL of Line
printf("%s", line);
fprintf(fp_write, "%s", line); // writing the entire line into the file
FLAG_FOUND = 1; // found something in the line?
}
}
if (!FLAG_FOUND) // if zero
printf("Sorry, no matches were found...\n");
fclose(fp_write);
fclose(fp);
return 0;
}
Explanation
The statement:
strstr(line, word_to_find) != NULL
Will only become NULL when it reaches NULL, in other words, the customer name should be given in the last position of lines.
My customer_info.txt is as follows:
PRICE SERVICE CUSTOMER_NAME
=========================================
1250.00 Premium John_Doe
750.00 Pro Pack Lorem_Ipsum
1800.00 Grand Johnny_Doe
The program works like:
$ g++ -o pro pro.cpp; ./pro
Enter a customer name to find: John_Doe
1250.00 Premium John_Doe // LET LINE_X
The mentioned LINE_X will be written into customers_new_added.txt (creates if doesn't exists).
customers_new_added.txt is as follows now:
1250.00 Premium John_Doe
The end of file must contain a new line or the last line will not be read.

Editing a specific value in a csv text file through C programming

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

Get one string with space first and get another after tabs

I want to get strings from a .txt file, reading lines that each has name and phone number. and two \t characters are between names and phone numbers.
Example:
name\t\t\tphone#
thomas jefferson\t\t054-892-5882
bill clinton\t\t054-518-6974
The code is like this;
FILE *f;
errno_t err;
treeNode *tree = NULL, temp;
char input, fileName[100];
//get file name
while (1){
printf("Enter input file name: ");
scanf_s("%s", fileName, 100);
//f = fopen(fileName, "r");
if(err = fopen_s(&f, fileName, "r"))
printf("Cannot find file!\n");
//if (f == NULL)
// printf("Cannot find file!\n");
else
break;
}
//save info into BST
fscanf_s(f, " NAME Phone #\n", 20);
while (fscanf_s(f, "%[^\t]s\t\t%[^\n]s",
temp.name, temp.phoneNo, 50, 30) != EOF)
bstInsert(tree, temp.name, temp.phoneNo);
fclose(f);
treeNode is a binary search tree struct, and bstInsert is a function to add a struct containing 2nd and 3rd parameters to a binary search tree.
after I get the name of the file with scanf_s, code stops at the fscanf_s statement, showing below on the debugger;
temp.name: invalid characters in string.
temp.phoneNo: ""
I don't know how [^\t] or [^\n] works exactly. Can anyone let me know how I can deal with this problem? Thanks in advance!
"Can anyone let me know how can I deal with this problem?" I am no fan of scanf and family, so I deal with the problem by using different methods. Following your lead of using fopen_s and scanf_s I have used the "safer" version of strtok which is strtok_s.
#include <stdio.h>
#include <string.h>
int main (void) {
FILE *f;
errno_t err;
char *pName, *pPhone;
char input[100], fileName[100];
char *next_token = NULL;
// get file name
do{
printf("Enter input file name: ");
scanf_s("%s", fileName, 100);
if(err = fopen_s(&f, fileName, "r"))
printf("Cannot find file!\n");
} while (err);
// read and process each line of the file
while(NULL != fgets(input, 100, f)) { // has trailing newline
// isolate name
pName = strtok_s(input, "\t\r\n", &next_token); // strip newline too
if (pName == NULL) // garbage trap
pName = "(Error)";
printf ("%-30s", pName);
// isolate phone number
pPhone = strtok_s(NULL, "\t\r\n", &next_token); // arg is NULL after initial call
if (pPhone == NULL)
pPhone = "(Error)";
printf ("%s", pPhone);
printf ("\n");
}
fclose(f);
return 0;
}
Program output using a file with your example data:
Enter input file name: test.txt
name phone#
thomas jefferson 054-892-5882
bill clinton 054-518-6974

Resources