I'm a newbie in C.
Could you help me please. There is a structure First name, Last Name, gender, age. Entries must be entered from the keyboard. I need to save this information in a file and then show on the screen all entries with gender == Male and save them in a separate file.
Thank you!
There is a code for reading a structure from file, but I can't understand how to check gender == Male.
#include "stdafx.h"
#include <cstdio>
int _tmain(int argc, _TCHAR* argv[])
{
FILE *file;
struct Person {
char name[20];
char gender[20];
unsigned age;
};
struct Person SinglePerson[10];
char i=0;
file = fopen("e:\\Test.txt", "r");
while (fscanf (file, "%s%s%u", SinglePerson[i].name, &(SinglePerson[i].gender), &(SinglePerson[i].age)) != EOF) {
printf("%s %s %u\n", SinglePerson[i].name, SinglePerson[i].gender, SinglePerson[i].age);
i++;
}
file = fopen("e:\\fprintf.txt", "w");
while (scanf ("%s%s%u", SinglePerson[i].name, &(SinglePerson[i].gender), &(SinglePerson[i].age)) != EOF) {
fprintf(file, "%s %s %u\n", SinglePerson[i].name, SinglePerson[i].gender, SinglePerson[i].age);
i++;
}
fread;
return 0;
}
Worked! I did it ))
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define M 2 // M plus 1 is equals to number of structres
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
FILE *file;
struct Person {
char name[20];
char gender[20];
unsigned age;
};
struct Person SinglePerson[1];
char i=0;
char counter = 0;
void InputFromKeyboard () {
file = fopen("Input.txt", "w");
while(scanf("%s%s%u", SinglePerson[i].name, SinglePerson[i].gender, &(SinglePerson[i].age)) == 3 && i <= M) {
fprintf(file, "%s %s %u\n", SinglePerson[i].name, SinglePerson[i].gender, SinglePerson[i].age);
counter++;
i++;
if (i == M+1) {
break;
}
}
fclose(file);
};
void OutputToFile () {
file = fopen("Output.txt", "w");
for (i = 0; i < counter; i++) {
if (strcmp(SinglePerson[i].gender, "Male") == 0) {
fprintf(file, "%s %s %u\n", SinglePerson[i].name, SinglePerson[i].gender, SinglePerson[i].age);
}
}
fclose(file);
}
void OutputToScreen () {
file = fopen("Output.txt", "r");
for (i = 0; i < counter; i++) {
if (strcmp(SinglePerson[i].gender, "Male") == 0) {
printf("%s %s %u\n", SinglePerson[i].name, SinglePerson[i].gender, SinglePerson[i].age);
}
}
fclose(file);
}
int main(int argc, char *argv[]) {
InputFromKeyboard();
OutputToFile();
OutputToScreen();
return 0;
}
Related
I am trying to store the values stored in a details.txt file into their appropriate place in a dynamically allocated struct. Am I doing something (that should be simple) incorrectly for this not to work? Is it necessary for me to use strtok and split by ','?
My details.txt reads:
mitch,8,1.78,burgers
murray,42,6.5,lasagna
travis,64,1.85,sushi
sam,12,1.94,bacon
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BUFFERSIZE 256
typedef struct
{
char name[BUFFERSIZE];
int favnumber;
float height;
char favfood[BUFFERSIZE];
} Person;
void print_person(Person *p)
{
printf("name: %s\n", p->name);
printf("num: %d\nheight: %.2f\nfav. food: %s\n\n",
p->favnumber, p->height, p->favfood);
}
int count_lines(FILE *fp)
{
int nlines = 0;
char c;
for (c = fgetc(fp); c != EOF; c = fgetc(fp))
{
if (c == '\n')
{
nlines++;
}
}
rewind(fp);
return nlines;
}
int main(void)
{
FILE *fp = fopen("details.txt", "r");
// count lines
int nlines = count_lines(fp);
printf("found %d lines\n\n",nlines);
Person *people = (Person*)malloc(nlines*sizeof(Person));
char buffer[BUFFERSIZE];
int i = 0;
while (fgets(buffer,BUFFERSIZE,fp) != NULL)
{
sscanf(buffer,"%s%d%f%s",people[i].name,
&(people[i].favnumber),
&(people[i].height),people[i].favfood);
print_person(&(people[i]));
i++;
}
printf("found %d people\n",i);
free(people);
fclose(fp);
}
Unfortunately, the current output of my program is:
found 4 lines
name: mitch,8,1.78,burgers
num: 0
height: 0.00
fav. food:
...
found 4 people
The problem is that the first %s parse the the whole line, and you need , in the format string to separate the fields. Not an issue here yet but I also used %[^,] for the last format string so it will not stop at the first space. Also added precision on the strings to avoid buffer overflows:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BUFFERSIZE 255
#define str(s) str2(s)
#define str2(s) #s
typedef struct
{
char name[BUFFERSIZE+1];
int favnumber;
float height;
char favfood[BUFFERSIZE+1];
} Person;
void print_person(Person *p)
{
printf("name: %s\n", p->name);
printf("num: %d\nheight: %.2f\nfav. food: %s\n\n",
p->favnumber, p->height, p->favfood);
}
int count_lines(FILE *fp)
{
int nlines = 0;
char c;
for (c = fgetc(fp); c != EOF; c = fgetc(fp))
{
if (c == '\n') {
nlines++;
}
}
rewind(fp);
return nlines;
}
int main(void)
{
FILE *fp = fopen("details.txt", "r");
// count lines
int nlines = count_lines(fp);
printf("found %d lines\n\n",nlines);
Person *people = (Person*)malloc(nlines*sizeof(Person));
char buffer[BUFFERSIZE+1];
int i = 0;
while (fgets(buffer,BUFFERSIZE+1,fp) != NULL)
{
// Changed line, see formatting of %s
sscanf(buffer,
"%" str(BUFFERSIZE) "[^,],%d,%f,%" str(BUFFERSSIZE) "[^,]",
people[i].name,
&(people[i].favnumber),
&(people[i].height),people[i].favfood);
print_person(&(people[i]));
i++;
}
printf("found %d people\n",i);
free(people);
fclose(fp);
}
I need to load strings from file into a struct array.
CORRECT OUTPUT:
4
Sarajevo,345123
Tuzla,123456
Mostar,101010
Banja Luka,234987
MY OUTPUT:
1
Sarajevo 345123
Tuzla 123456
Mostar 101010
Banja Luka 234987,544366964
Code:
#include <stdio.h>
#include <string.h>
struct City {
char name[31];
int number_of_citizen;
};
int load(struct City cities[100], int n) {
FILE *fp = fopen("cities.txt", "r");
int i = 0;
while (fscanf(fp, "%[^,]s %d\n", cities[i].name, &cities[i].number_of_citizen)) {
i++;
if (i == n)break;
if (feof(fp))break;
}
fclose(fp);
return i;
}
int main() {
int i, number_of_cities;
struct City cities[10];
FILE* fp = fopen("cities.txt", "w");
fputs("Sarajevo 345123", fp); fputc(10, fp);
fputs("Tuzla 123456", fp); fputc(10, fp);
fputs("Mostar 101010", fp); fputc(10, fp);
fputs("Banja Luka 234987", fp);
fclose(fp);
number_of_cities = load(cities, 10);
printf("%d\n", number_of_cities);
for (i = 0; i < number_of_cities; i++)
printf("%s,%d\n", cities[i].name, cities[i].number_of_citizen);
return 0;
}
Could you explain me how to fix this? Why my program only loaded 1 city?
The fscanf() conversion string is incorrect: instead of "%[^,]s %d\n" you should use:
while (i < n && fscanf(fp, "%30[^,],%d",
cities[i].name,
&cities[i].number_of_citizen) == 2) {
i++;
}
Or better:
#include <errno.h>
#include <stdio.h>
#include <string.h>
int load(struct City cities[], int n) {
char buf[200];
int i = 0;
char ch[2];
FILE *fp = fopen("cities.txt", "r");
if (fp == NULL) {
fprintf(stderr, "cannot open %s: %s\n", "cities.txt",
strerror(errno));
return -1;
}
while (i < n && fgets(buf, sizeof buf, fp)) {
if (sscanf(buf, "%30[^,],%d%1[\n]",
cities[i].name,
&cities[i].number_of_citizen, ch) == 3) {
i++;
} else {
fprintf(stderr, "invalid record: %s\n", buf);
}
}
fclose(fp);
return i;
}
Also change your main function to output commas between the city names and population counts:
int main() {
int i, number_of_cities;
struct City cities[10];
FILE *fp = fopen("cities.txt", "w");
if (fp) {
fputs("Sarajevo,345123\n", fp);
fputs("Tuzla,123456\n", fp);
fputs("Mostar,101010\n", fp);
fputs("Banja Luka,234987\n", fp);
fclose(fp);
}
number_of_cities = load(cities, 10);
printf("%d\n", number_of_cities);
for (i = 0; i < number_of_cities; i++)
printf("%s,%d\n", cities[i].name, cities[i].number_of_citizen);
return 0;
}
EDIT: since there are no commas in the database file, you must use a different parsing approach:
#include <errno.h>
#include <stdio.h>
#include <string.h>
int load(struct City cities[], int n) {
char buf[200];
int i = 0;
FILE *fp = fopen("cities.txt", "r");
if (fp == NULL) {
fprintf(stderr, "cannot open %s: %s\n", "cities.txt",
strerror(errno));
return -1;
}
while (i < n && fgets(buf, sizeof buf, fp)) {
/* locate the last space */
char *p = strrchr(buf, ' ');
if (p != NULL) {
/* convert it to a comma */
*p = ',';
/* convert the modified line */
if (sscanf(buf, "%30[^,],%d",
cities[i].name,
&cities[i].number_of_citizen) == 2) {
i++;
continue;
}
}
fprintf(stderr, "invalid record: %s", buf);
}
fclose(fp);
return i;
}
Description: program read data from 2 files, store them in structs,ask user for (city or place of residence), if city name matches with that stored in file, program displays output(student, national_ID,name) and store in a file.
My question is that, the above code that i wrote does not work. it gives me a "no information" even when i enter a city which is on the file.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_LEN 20
#define MAX_LINE 7
typedef struct studentdata
{
char NATIONAL_ID[20];
char NAME[20];
char STUDENT_CODE[20];
char CITY[20];
}studentdata;
int main(void)
{
int i;
char x=0, CITY[MAX_LEN];
studentdata y[MAX_LINE];
char temp[20];
char temp1[20];
char count=0;
FILE *fi = fopen("employee1.txt", "r");
if (fi == NULL)
{
printf("error data");
exit(0);
}
FILE *fp = fopen("student1.txt", "r");
if (fp == NULL)
{
printf("error data1");
exit(1);
}
i = 0;
printf("Enter city\n");
scanf("%s",CITY);
//i = 0;
FILE *fa = fopen("student2.txt", "w");
if (fa == NULL)
{
printf("error data2");
exit(2);
}
while(fscanf(fi, "%s %s %s", y[i].NATIONAL_ID, y[i].NAME, y[i].STUDENT_CODE) == 4)
i++;
count=i;
I am sure the error is within this loop but can't just find it.
while(fscanf(fp, "%s %s", temp,temp1) == 2)
{
for(i=0; i< count;i++)
{
if (strcmp(y[i].NATIONAL_ID,temp)==0)
{
strcpy(y[i].CITY,temp1);
if (strcmp(y[i].CITY,CITY)==0)
{
fprintf( "%s\t %s\t %s\t %s\t\n", y[i].NATIONAL_ID, y[i].NAME, y[i].STUDENT_CODE, y[i].CITY);
x++;
}
}
}
}
fclose(fa);
if(!x)
{
printf("no information\n");
}
fclose(fi);
fclose(fp);
return 0;
}
I would say that nothing is being read from file into the in first while loop -
while(fscanf(fi, "%s %s %s", y[i].NATIONAL_ID, y[i].NAME, y[i].STUDENT_CODE) == 4)
i++;
As you match for 3 arguments but checks fscanf's return against 4 which will be false and loop will not iterate and i remains 0 , so as count.
Therefore , your this inner loop won't run-
for(i=0; i< count;i++) //count=0
and thus you don't get your output .
Modify your loop to -
while (fscanf(fi, "%s %s %s", y[i].NATIONAL_ID, y[i].NAME, y[i].STUDENT_CODE) ==3)
/* see fscanf's return is checked against 3 */
i++;
Note that an easy way to spot this problem would be to print the information as it is read, or print the array after the read is complete.
I'm trying to search a file containing information on a group of people, for example: their first name, last name and ID.
I'm prompting the user to enter their ID code. The program should search the text file and ensure that their code matches the one within the file so that the program can continue by comparing the string from the file and the variable inputted by the user.
I'm not sure how to implement this. Below is a snippet of the code:
#include <stdio.h>
#include <conio.h>
#include <string.h>
typedef struct record {
char (fname[3])[20];
char (lname[3])[20];
int code[3];
} information;
int main (void) {
char ffname[20], flname[20];
int fID, i;
FILE *kfile;
if ((kfile = fopen("C:\\Users\\Student\\Downloads\\information.txt","r")) == NULL) {
perror("Error while opening file");
} else {
printf("%-20s %-20s %s\n", "First Name", "Last Name", "ID");
fscanf(kfile, "%19s %19s %d", ffname, flname, &fID);
printf("\n");
while (!feof(kfile)) {
printf("%-20s %-20s %04d\n", ffname, flname, fID);
fscanf(kfile, "%19s %19s %d", ffname, flname, &fID);
}
fclose(kfile);
}
information info;
for (i = 0; i < 3; i++) {
printf("Please enter your ID.");
scanf("%04d", &info.code);
}
getch();
return 0;
}
I'm not sure I understand your problem, but you can try this:
typedef struct record {
char *fname;
char *lname;
int code;
} information;
int main (void) {
char ffname[28], flname[28];
int fID, i, id_;
information array[3];
FILE *kfile;
i = 0;
if ((kfile = fopen("C:\\Users\\Student\\Downloads\\information.txt","r")) == NULL) {
perror("Error while opening file");
} else {
while (!feof(kfile)) {
fscanf(kfile, "%s %s %d", ffname, flname, &fID);
array[i].fname = strdup(ffname);
array[i].lname = strdup(flname);
array[i].code = fID;
i++;
}
fclose(kfile);
}
printf("Please enter your ID: ");
scanf("%d", &id_);
for (i = 0; i < 3; i++) {
if (array[i].code == id_) {
// print the record
printf("%s %s \n", array[i].fname, array[i].lname);
}
}
return 0;
}
I'm having issues with fprintf in my RPC program. It opens a file but won't read the content into a file. It will print the content using printf but fprint leaves the file blank. How do I fix this issue? Thank you
#include <rpc/rpc.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include"lab5.h"
char * filename(char *str)
{
file = str;
printf("filename = %s\n",file);
return file;
}
int writefile(char *content)
{
FILE *fp1;
fp1 = fopen("recfile.txt", "w");
if(fp1 == NULL)
{
printf("File can't be created\n");
return 0;
}
printf("%s\n",content);
int i = fprintf(fp1, "%s", content);
printf("i = %d\n",i);
close(fp1);
return 1;
}
int findwordcount(char* searchword)
{
char *grep;
int count;
int status;
FILE *fp;
grep = (char*)calloc(150, sizeof(char));
strcpy(grep, "grep -c \"");
strcat(grep, searchword);
strcat(grep, "\" ");
strcat(grep, "recfile.txt");
strcat(grep, " > wordcount.txt");
status = system(grep);
printf("status = %d\n", status);
if(status != 0)
{
count = 0;
}
else
{
fp = fopen("wordcount.txt", "r");
fscanf(fp, "%d", &count);
printf("count = %d\n", count);
}
return count;
}
In your function int writefile (char *content); you are currently using close(fp1);. Instead to close the file, you should fclose(fp1) instead.