Extract the line from the file, concatenate it with a certain string problem - concatenation

I have a problem, in the text file I have the form "User:Username Password,Real name Real Surname Email" and so on several lines, how can I add the word "(suspended)" to the beginning of a specific line?
My code does this:
"U(suspended)ser:Username Password,Real name Real Surname Email"
How to fix it,to get?
"(suspended)User:Username Password,Real name Real Surname Email"
Here's code:
char username_to_suspend[50];
scanf("%s",username_to_suspend);
char line[100];
char new_line[sizeof(line)]="(suspended) ";
FILE *fp = fopen("users.txt", "r+");
while(fgets(line,sizeof(line),fp)!=NULL)
{
if(strstr(line,username_to_suspend)!=NULL)
{
strcat(new_line,&line[1]);
fseek(fp, -strlen(line), SEEK_CUR);
fputs(new_line, fp);
}
else
{
continue;
}
break;
}
fclose(fp);
Thanks in advance!
Best regards!

Related

How do I search a record using an integer from a file?

Currently, I can only search using a string but I don't know how to search a record when the user inputs a 12 digit number (long long data type). I tried to write if(identityC == line) where the original if(strcmp(....) code was at but I didn't get it to work. Any solutions?
char line[255], name[30];
long long identityC;
FILE* fpointer = fopen("123 Hotel Customer.txt", "r");
//printf("\nPlease Enter Your Identity Card Number: ");
//scanf("%lld", &identityC);
printf("\nPlease Enter your Name to Search your Room Booking: ");
scanf("%s", &name);
while (!feof(fpointer))
{
fgets(line, 255, fpointer);
if (strncmp(name, line, strlen(name)) == 0)
printf("%s", line);
}
fclose(fpointer);
return;
Note: The purpose is to show a way to get started with working with files.
Assuming you store information in your file in this format,
roomno,Hotel Name,Customer name,isOccupied
datatype: int, string, string, bool
you can do this-
FILE* file = fopen("filename.txt","w");
char buffer[512];
while(fgets(buffer, 512, file)!=NULL){
int roomNo = strtok(buffer, "\n,");
char* hotel_name = strtok(NULL, "\n,");
char* customer_name = strtok(NULL, "\n,");
bool isOccupied = strtok(NULL, "\n,");
// Now you are done extracting values from file. Now do any work with them.
}
Here is information on strtok() and fgets().
Also, from Steve Summit, Why is while (!feof (file) ) always wrong?

How to store two lines in a text file into two strings

I'm trying to read a text file that will contain two lines, something like this:
18,3,4,c;19,3,5,D
19100,18,18;19102,3,2
and i want to store the first line in a string called Students and the second one into another string called Courses.
I have wrote this code but it stores one line only and i can't get it to work with the second line
FILE *fptr;
if ((fptr = fopen("program.txt", "r")) == NULL) {
printf("Error! opening file");
exit(1);
}
fscanf(fptr, "%[^\n]", Students);
fclose(fptr);
Can anyone help me with that? I'm a newbie to c and i can't get how to do so, Thank you in advance.
FILE *fptr;
char buffer[255] = {'\0'};
if ((fptr = fopen("program.txt", "r")) == NULL) {
printf("Error! opening file");
exit(1);
}
fgets(Students, sizeof(Students), fptr);
fgets(Courses, sizeof(Courses), fptr);
fclose(fptr);
This line fgets(Students, sizeof(Students), fptr); will start reading from the begginning of the file and store the first line to Students char array & then fgets(Courses, sizeof(Courses), fptr); will read the second line and store it into Courses char array.
Make sure that the size of Students & Courses is large enough to accommodate each line into them.
You may try fscanf() for the problem:
#include <stdio.h>
int main(void) {
char Students[100], Courses[100];
FILE *fp = fopen("program.txt", "r");
if (!fp) {
printf("File wasn't opened.\n");
return -1;
}
fscanf(fp, "%s \n", Students);
fscanf(fp, "%s", Courses);
printf("%s\n", Students);
printf("%s\n", Courses);
fclose(fp);
return 0;
}
My program.txt contains:
John_Doe
Mathematics
Sample Output
John_Doe // Students
Mathematics // Courses
Use something like:
fscanf(fptr, "%[^\n]\n%[^\n]]\n", Students,Courses);
Where you tell scanf() to read up to a new-line, read and discard the new line, then do it again.

How can I run through this text file and use strtok() to extract numbers and store the numbers in a different file?

This is a homework problem for my C class. We are learning file I/O and I have successfully opened both files and now I have to use strtok() on the first file to extract number data and store it in a different file. I have successfully taken the numbers from the first line of the text file and stored them in the other file, but I can't get strtok() to run through the entire file. Any suggestions?
Not a whole lot...I'm drawing a blank here. I've tried to use " \n" so that the delimiter is both space and newline, but I don't think that it works...I thought that I could only have 1 delimiter anyway.
void main()
{
FILE *fp1 = NULL;
FILE *fp2 = NULL;
int i;
char strwarehouse[100];
char *token;
printf("Scanning files and parsing strings....\n");
fp1 = fopen("Assign9.txt", "r");
fp2 = fopen("numfile.txt", "w");
if (fp1 == NULL)
{
printf("ERROR OPENING FILE, TERMINATING PROGRAM\n");
}
else
{
fgets(strwarehouse, 100, fp1);
token = strtok(strwarehouse, " \n");
while (token != NULL)
{
if (isdigit(token[0]))
{
fprintf(fp2, "%s ", token);
}
token = strtok(NULL, " \n");
}
fclose(fp2);
fclose(fp1);
}

Read specific line from different text files in C programming

Alright so i'm still learning C programming and what im trying to do is read a specific line from different text files in the same folder. So what i mean to say is lets say i want to read the names from different text files and display them. Ive been trying to do it but im only able to read text from one file at a time
below is my code
void display_medicine()
{
system("cls");
const char *fil = "Medicines/";
const char *exec = ".txt";
char filename[50];
//snprintf(filename, sizeof filename, "%s%s%s", fil, medicineview, exec);
system("cls");
char medicinename[50];
char medavailability[20];
char companyname[100];
char dom[25];
char doe[50];
char price[20];
FILE *file;
file =fopen(filename,"r");
int num = 1;
if (file)
{
fgets(medicinename, sizeof(medicinename), file);
fgets(medavailability, sizeof(medavailability), file);
fgets(companyname, sizeof(companyname), file);
fgets(dom, sizeof(dom), file);
fgets(doe, sizeof(doe), file);
fgets(price, sizeof(price),file);
fclose(file);
gotoxy(10,3);
printf("================= %s VIEWING ================" "\n");
gotoxy(14,5);
printf("Name:\t\t\t%s", medicinename);
gotoxy(14,7);
printf("Availability:\t\t%s", medavailability);
gotoxy(14,9);
printf("Company Name:\t\t%s", companyname);
gotoxy(14,11);
printf("Date of Manufacture:\t%s", dom);
gotoxy(14,13);
printf("Date of Expiry:\t\t%s", doe);
gotoxy(14,15);
printf("Price:\t\t\t%s\n",price);
gotoxy(10,17);
printf("===============================================");
gotoxy(10,19);
printf("Press any key to go back!");
getch();
customerMenu();
}
Im able to read stuff only from one text file but not the others
Any help would be much appreciated

Two words in a string from text file

I'm trying to get two words in a string and I don't know how I can do it. I tried but if in a text file I have 'name Penny Marie' it gives me :name Penny. How can I get Penny Marie in s1? Thank you
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("Hello world!\n");
char s[50];
char s1[20];
FILE* fp = fopen("file.txt", "rt");
if (fp == NULL)
return 0;
fscanf(fp,"%s %s",s,s1);
{
printf("%s\n",s);
printf("%s",s1);
}
fclose(fp);
return 0;
}
Change the fscanf format, just tell it to not stop reading until new line:
fscanf(fp,"%s %[^\n]s",s,s1);
You shall use fgets.
Or you can try to do this :
fscanf(fp,"%s %s %s", s0, s, s1);
{
printf("%s\n",s);
printf("%s",s1);
}
and declare s0 as a void*
The other answers address adjustments to your fscanf call specific to your stated need. (Although fscanf() is not generally the best way to do what you are asking.) Your question is specific about getting 2 words, Penny & Marie, from a line in a file that contains: name Penny Marie. And as asked in comments, what if the file contains more than 1 line that needs to be parsed, or the name strings contain a variable number of names. Generally, the following functions and techniques are more suitable and are more commonly used to read content from a file and parse its content into strings:
fopen() and its arguments.
fgets()
strtok() (or strtok_r())
How to determine count of lines in a file (useful for creating an array of strings)
How to read lines of file into array of strings.
Deploying these techniques and functions can be adapted in many ways to parse content from files. To illustrate, a small example using these techniques is implemented below that will handle your stated needs, including multiple lines per file and variable numbers of names in each line.
Given File: names.txt in local directory:
name Penny Marie
name Jerry Smith
name Anthony James
name William Begoin
name Billy Jay Smith
name Jill Garner
name Cyndi Elm
name Bill Jones
name Ella Fitz Bella Jay
name Jerry
The following reads a file to characterize its contents in terms of number of lines, and longest line, creates an array of strings then populates each string in the array with names in the file, regardless the number of parts of the name.
int main(void)
{
// get count of lines in file:
int longest=0, i;
int count = count_of_lines(".\\names.txt", &longest);
// create array of strings with information from above
char names[count][longest+2]; // +2 - newline and NULL
char temp[longest+2];
char *tok;
FILE *fp = fopen(".\\names.txt", "r");
if(fp)
{
for(i=0;i<count;i++)
{
if(fgets(temp, longest+2, fp))// read next line
{
tok = strtok(temp, " \n"); // throw away "name" and space
if(tok)
{
tok = strtok(NULL, " \n");//capture first name of line.
if(tok)
{
strcpy(names[i], tok); // write first name element to string.
tok = strtok(NULL, " \n");
while(tok) // continue until all name elements in line are read
{ //concatenate remaining name elements
strcat(names[i], " ");// add space between name elements
strcat(names[i], tok);// next name element
tok = strtok(NULL, " \n");
}
}
}
}
}
}
return 0;
}
// returns count, and passes back longest
int count_of_lines(char *filename, int *longest)
{
int count = 0;
int len=0, lenKeep=0;
int c;
FILE *fp = fopen(filename, "r");
if(fp)
{
c = getc(fp);
while(c != EOF)
{
if(c != '\n')
{
len++;
}
else
{
lenKeep = (len < lenKeep) ? lenKeep : len;
len = 0;
count++;
}
c = getc(fp);
}
fclose(fp);
*longest = lenKeep;
}
return count;
}
Change your fscanf line to fscanf(fp, "%s %s %s", s, s1, s2).
Then you can printf your s1 and s2 variables to get "Penny" and "Marie".
Try the function fgets
fp = fopen("file.txt" , "r");
if(fp == NULL) {
perror("Error opening file");
return(-1);
}
if( fgets (str, 60, fp)!=NULL ) {
/* writing content to stdout */
puts(str);
}
fclose(fp);
In the above piece of code it will write out the content with the maximum of 60 characters. You can make that part dynamic with str(len) if I'm not mistaken.

Resources