I was creating on a very basic program in C which takes a word from user as input and searches for how many times it appears in a text file and gives output.
The code is:
#include<stdio.h>
#include<string.h>
int main()
{
char user[20];
char word[20];
int i,pos=0,sum=0;
char c;
c='a';
printf("Enter the word you want to look for\n");
gets(user);
FILE *p;
p=fopen("D:\\trees.txt","r+");
do
{
pos=0;
fscanf(p,"%s",word);
if(c!=EOF)
{
if(strlen(word)==strlen(user))
{
for(i=0;i<strlen(user);i++)
{
if(word[i]==user[i]||word[i]==user[i]+32||word[i]==user[i]-32)
{
}
else
{
pos=1;
break;
}
}
}
else
{
pos=1;
}
if(pos=0)
{
sum++;
}
}
}
while(c!=EOF)
;printf("\nNumber of times %s appears is %d",user,sum);
fclose(p);
}
Now the program takes the input fine, but doesn't give any output.
Looks like this:
What have I done wrong?
Looking at the comments, your code should be something like:
#include<stdio.h>
#include<string.h>
#include <ctype.h>
int main()
{
char user[20];
char word[20];
int n, pos=0, sum=0;
unsigned int i, l;
FILE *p;
do {
printf("Enter the word you want to look for\n");
} while (gets(user)==0);
user[strlen(user)-1]= '\0'; // remove trailing \n
if ((p=fopen("D:\\trees.txt","r+"))==0) {printf("Error opening file\n"); exit(0);}
do
{
pos=0;
n= fscanf(p,"%s",word);
if (n==1)
{
if(strlen(word)==(l=strlen(user)))
{
for(i=0; i<l; i++)
{
if(!(word[i]==user[i]||word[i]==tolower(user[i])||word[i]==toupper(user[i])))
{
pos=1;
break;
}
}
}
else pos=1;
if(pos==0) sum++;
}
}
while(n==1);
printf("\nNumber of times %s appears is %d",user,sum);
fclose(p);
return(1);
}
(with some optimizations and additions)
Related
I'm trying to write a program which encrypts a input file and creates an output file after the encryption.
The fprintf does work fine if I write to stdout but when I send the output to a file, only the last fprintf output is written into the file, i.e. if the input file contains 2 lines, the output file contains only the last line encrypted.
Source:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define Max 1024
int menu()
{
printf("To encrypt, input e or E\n");
printf("To decrypt, input d or D\n");
printf("To exit, input any other letter\n");
printf("Please enter your choice and hit return:\n");
return 0;
}
void encrypto(char*str)
{
FILE *ausgabeverschl;
ausgabeverschl=fopen("encrypted.txt","w");
int n=0;
char *p=str ,q[Max];
while(*p)
{
if(islower(*p))
{
if((*p>='a')&&(*p<'x'))
q[n]=toupper(*p + (char)3);
}
else
{
q[n]=*p+(char)3;
}
n++; p++;
}
q[n++]='\0';
fprintf(ausgabeverschl, "%s\n", q); // problem occurs here
fclose(ausgabeverschl);
}
void decrypto(char*str)
{
FILE *ausgabeunverschl;
ausgabeunverschl=fopen("decrypted.txt","w");
int n=0;
char *p=str, q[Max];
while(*p)
{
if(isupper(*p))
{
if((*p>='D')&&(*p<='Z'))
q[n]=tolower(*p - (char)3);
}
else
{
q[n]=*p-(char)3;
}
n++; p++;
}
q[n++]='\0';
fprintf(ausgabeunverschl,"%s\n",q);
fclose(ausgabeunverschl);
}
int main()
{
char einlesestring[Max];
char choice[2];
FILE *ein;
ein=fopen("text.txt","r");
if(ein!=NULL)
{
printf("\nFile found.\n\n");
}
if(ein==NULL)
{
printf("No file found.\n");
return 1;
}
int counter=0;
char stringlaenge[Max];
while (fgets(stringlaenge, Max, ein) != NULL)
{
counter++;
}
printf(„Counted lines: %d\n", counter);
rewind(ein);
menu();
gets(choice);
if((choice[0]=='e')||(choice[0]=='E'))
{
while(fgets(einlesestring, Max, ein)!= NULL)
{
encrypto(einlesestring);
}
}
else if((choice[0]=='d')||(choice[0]=='D'))
{
while(fgets(einlesestring,Max, ein)!=NULL)
{
decrypto(einlesestring);
}
}
fclose(ein);
return 0;}
Thanks for helping!
I am having trouble with segmentation fault (core dumped) in C. I am compiling using gcc, and I can't seem to fix it! Here is the code, which is supposed to look at a csv file and perform 1 of 4 opperations:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, const char * argv[])
{
int lines=0, i=0, a=0;
char strings[128], *broken=" ", *array[100][4], *err=" ";
FILE *file;
file=fopen("inventory.csv", "a+");
broken= malloc(1000);
err=malloc(100);
while(fgets(strings, sizeof strings, file)!=NULL){
++lines;
a=0;
broken=strtok(strings, ",");
while(broken!=NULL){
strcpy( array[i][a], broken);
a++;
}
i++;
}
if(strcmp(argv[1], "list")==0){
printf("Name, Quantity, Reorder limit, Cost");
while(fgets(strings, sizeof strings, file)!=NULL){
while(broken!=NULL){
printf("%s, ", array[i][a]);
}
printf("\n");
}
}
else if(strcmp(argv[1], "reorder")==0){
int i=0;
printf("We need to purchase more of the following items: \n");
for(i=0;i<lines;i++){
if(strtod(array[i][1], &err)<=strtod(array[i][2],&err)){
printf("%s\n", array[i][0]);
}
}
}
else if(strcmp(argv[1], "deduct")==0){
if(argv[2]){
int i=0;
char str[100];
for(i=0;i<lines;i++){
if(strcmp(argv[2], array[i][0])==0){
if(strtod(array[i][1],&err)-1>0){
sprintf(str,"%f",strtod(array[i][1],&err)-1);
array[i][1]=str;
printf("Success\n");
fseek(file, 0, 1);
sprintf(str,"%s,%s,%s,%s", array[i][0], array[i][1],
array[i][2], array[i][3]);
fwrite(str,1,sizeof(str),file);
}
else{
printf("There are none left!\n");
}
}
}
}
else{
printf("Enter a food item");
}
}
else if(strcmp(argv[1], "add")==0){
fseek(file, 0, 2);
char str[100];
sprintf(str,"%s,%s,%s,%s\n",argv[2],argv[3],argv[4],argv[5]);
fwrite(str,1,sizeof(str),file);
}
else{
printf("Please enter an argument: list, reorder, deduct _name_, add _name_
_qty_ _reorderlimit_ _price_\n");
}
fclose(file);
return 0;
}
There is no way to get out of the while loop.
I would write one more strtok in:
broken=strtok(strings, ",");
while(broken!=NULL){
strcpy( array[i][a], broken);
broken=strtok(NULL,",");
a++;
}
I am writing a program in c to identify functions' signature and copy in another file.
Idea was to determine parenthesis in any line and to copy that line to a file.
Afterwards we can check for return type and parameters, so as to differentiate constructs if, while from user defined functions except main.
But my code stuck in infinite loop. Can't find the problem.
find_sig.c
#include <stdio.h>
int main()
{
int count=0;
char c;
FILE *f1,*f2;
f1=fopen("input.c","r");
f2=fopen("output.c","w");
while((c=getc(f1))!=EOF)
{
do
{
if(c=='(')
{
fseek(f1,-count,1);
do{
putc(c,f2);
}while((c=getc(f1))!=')');
count=0;
}
else
count++;
}while((c=getc(f1))!=10);
count=0;
}
fclose(f1);
fclose(f2);
return 0;
}
input.c
#include<stdio.h>
void fun();
int main()
{
fun();
return 0;
}
void fun()
{
printf("hello");
}
Any other idea for determining functions' signature will be very helpful.
i figured it out.
#include<stdio.h>
#include<string.h>
char str1[50];
int count=0,i=0;
int main()
{
char c;
FILE *f1,*f2;
f1=fopen("input.c","r");
f2=fopen("output.c","w");
while((c=getc(f1))!=EOF)
{
if(c!=10) //checks for /n
{
if(c=='(')
{
++count;
fseek(f1,-count,1); //moves f1 to 'count' bytes back i.e. beginning of line
i=0;
while((c=getc(f1))!=';'&&c!='{') //checks for declaration or definition
{
str1[i++]=c;
}
if(strstr(str1,"main(")!=NULL) //checks whether str1 contains main
return 0;
else
{
fprintf(f2,"%s",str1); // copies str1 in f2
count=0;
}
}
else
count++;
}
else
count=0;
if(c==10)
putc(c,f2);
}
fclose(f1);
fclose(f2);
return 0;
}
I don't understand what I'm doing wrong here. I have a program that successfully reads in data from a file. Once it does this the data that was read in SHOULD be able to be searched/shown/or deleted, but it does not do this. I know the file is being successfully read because when I add a printf() to the function reading the file, it prints out the correct data. Help would be wonderful. Here is the stripped down version of the code.
typedef struct friends_contact{
char *First_Name;
char *Last_Name;
char *home;
char *cell;
}fr;
int main()
{
fr friends[5];
char buffer[BUFFSIZE];
int counter=0;
int i=0;
menu(friends, &counter,i,buffer);
getch();
return 0;
}
//Menu function
void menu(fr*friends,int* counter, int i,char buffer[])
{
int user_entry=0;
int user_entry1=0;
int user_entry2=0;
char user_entry3[50]={'\0'};
FILE *read;
printf("Welcome! Would you like to import a file? (1)Yes or (2) No");
scanf("%d",&user_entry1);
if(user_entry1==1)
{
printf("Please enter a file name");
scanf("%s",user_entry3);
read=fopen(user_entry3,"r");
}else;
do{
int result;
printf("\nPhone Book Application\n");
printf("1) Add friend\n2) Delete friend\n3) Show a friend\n4) Show phonebook\n5)Exit\n");
scanf("%d", &user_entry);
if(user_entry==1)
{
add_contact(friends,counter,i,buffer);
}
if(user_entry==2)
{
delete_contact(friends ,counter,i);
}
if(user_entry==3)
{
result=show_contact(friends ,counter,i);
if(result==0){
printf("\nName not Found\n");
}else{
result;
}
}
if(user_entry==4)
{
print_contact(friends, counter,i,user_entry3);
if(user_entry1==1)
{
file2(friends ,counter,i,buffer,read);
}else;
}
}while(user_entry!=5);
}
The delete function
//This is used to delete a name out of the book
char delete_contact(fr*friends ,int* counter, int i)
{
char name_search[50]={'\0'};
char Delete[5]={'\0'};
printf("Search by last name\n");
scanf("%s",name_search);//Name entry
for(i=0;i<*counter;i++)
{
if(strcmp(name_search,friends[i].Last_Name)==0)//Copys over the name entered
{
strcpy(friends[i].Last_Name,Delete);
}
}
//Freeing up memory.
free(friends[i].First_Name);
free(friends[i].Last_Name);
free(friends[i].home);
free(friends[i].cell);
printf("\nName(s) has been deleted\n");
}
the print function:
//This function prints out all the contact information
void print_contact(fr*friends ,int* counter, int i,char user_entry3[50])
{
for( i = 0; i < *counter; i++)
if (strlen(friends[i].First_Name) && strlen(friends[i].Last_Name)&& strlen(friends[i].home)&& strlen(friends[i].cell ))
{
getFirst(friends, i);
getLast(friends, i);
getHome(friends, i);
getCell(friends, i);
}
}
//Displays the contact in which you are searching for.
int show_contact(fr*friends ,int* counter, int i)
{
char name_search2[50]={'\0'};
int flag=0;
printf("Please enter a last name\n");
scanf("%s",name_search2);
for(i=0;i<*counter;i++)
{
//If the name is found, it reaturns the contact info.Now works for duplicate last names.
if(strcmp(name_search2,friends[i].Last_Name)==0)
{
(strlen(friends[i].First_Name) && strlen(friends[i].Last_Name)&& strlen(friends[i].home)&& strlen(friends[i].cell ));
getFirst(friends, i);
getLast(friends, i);
getHome(friends, i);
getCell(friends, i);
flag++;
}
}
return flag;
}
The Read in function:
void file2(fr*friends ,int* counter, int i,char buffer[],FILE*read)
{
fseek(read, 0, SEEK_SET);
while (fscanf(read,"%s", buffer) != EOF)
{
friends[*counter].Last_Name=malloc(BUFFSIZE*strlen(buffer));
strcpy(friends[*counter].Last_Name, buffer);
printf("%s\n",friends[*counter].Last_Name);
}
}
Try changing your read function to something like this where you pass in the size of your friends array so you don't read in too many lines and end up crashing your program. This is assuming you are reading in line by line from a text file.
This will loop while our counter is less than the number of elements in our friends array to ensure we don't go out of bounds while accessing each of the structures, OR if we reached the end of file, then it will stop.
To allocate memory for Last_Name we take the length of the string that got stored in buffer and add 1 to make room for the null terminating byte.
void file2(fr *friends, const size_t num_friends, FILE *read)
{
size_t counter = 0;
char buffer[128];
while (counter < num_friends && fscanf(read, "%s", buffer) != EOF) {
friends[counter].Last_Name = malloc(strlen(buffer) + 1);
strcpy(friends[counter].Last_Name, buffer);
counter++;
}
}
Then call this like file2(friends, 5, read); The middle argument is the size of your array.
fscanf can also overflow your buffer if you supply it with too much data. It has no bounds checking which can lead to crashing your program. I'd look into using fgets instead for next time.
I tried to make a program that writes struct elements to binary file and then writes the unique elements from the first file to another binary file. I compiled it with gcc and it works very good, but with MinGW the program freezes when it tries to open and create the second file. Do you have any idea where is the problem?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct element{
char name[80];
int p;
}ELEM;
void clear_stdin()
{
char str[255];
fgets(str,255,stdin);
}
int create()
{
FILE *f;
int d=0;
int c;
int n=0;
ELEM s;
f=fopen("file.bin","wb");
if(f==NULL)
{
printf("create(): Could not open file.bin for read\n");
return;
}
do{
printf("Add elements to file?:\n1 - yes\n2 - no\n");
scanf("%d",&c);
if (c==1)
{
printf("Name=");
clear_stdin();
fgets(s.name,80,stdin);
printf("P=");
scanf("%d",&s.p);
fwrite(&s,sizeof(ELEM),1,f);
n++;
}
else
d=1;
} while(d==0);
fclose(f);
return n;
}
void show(int n)
{
FILE *f;
ELEM s;
int i=0;
if(n==0)
return;
f=fopen("file.bin","rb");
while(i<n)
{
fread(&s,sizeof(ELEM),1,f);
puts(s.name);
printf("\t%d\n",s.p);
i++;
}
fclose(f);
}
int add(int n)
{
FILE *f;
int d=0;
int c;
ELEM s;
f=fopen("file.bin","ab");
if(f==NULL)
{
printf("add(): Could not open file.bin for append\n");
return;
}
do{
printf("Add elements to file?:\n1 - yes\n2 - no\n");
scanf("%d",&c);
if (c==1)
{
printf("Name=");
clear_stdin();
fgets(s.name,80,stdin);
printf("P=");
scanf("%d",&s.p);
fwrite(&s,sizeof(ELEM),1,f);
n++;
}
else
d=1;
} while(d==0);
fclose(f);
return n;
}
void func(int n)
{
FILE *f,*g;
ELEM v[20],w;
int i=0,j,k,x=0,s,gn=0,test;
f=fopen("file.bin","rb");
g=fopen("aux.bin","wb");
if((g==NULL)||(f==NULL))
{
if(g==NULL)
printf("function() : Could not open aux.bin for write\n");
if(f==NULL)
printf("function() : Could not open file.bin for read\n");
return;
}
i=0;
while(i<n)
{
fread(&v[i],sizeof(ELEM),1,f);
i++;
}
for(j=0;j<n;j++)
{
for(k=j+1;k<n;k++)
{
if(v[j].p==v[k].p)
x=1;
}
if(x==0)
{
s=strcmp(v[j].name,v[k].name);
if(s!=0)
{
fwrite(&v[j],sizeof(ELEM),1,g);
fread(&w,sizeof(ELEM),1,g);
gn++;
}
}
x=0;
}
test=fclose(g);
if(test!=0)
printf("function() : failed to closed file g\n");
test=fclose(f);
if(test!=0)
printf("function() : failed to closed file f\n");
g=fopen("aux.bin","rb");
if(g==NULL)
{
printf("function() : Could not open aux.bin for read\n");
return;
}
if(gn==0)
return;
i=0;
while(i<gn)
{
fread(&w,sizeof(ELEM),1,g);
puts(w.name);
printf("\t%d\n",w.p);
i++;
}
fclose(g);
}
int main()
{
int k=0,r,n;
do{
printf("1 - create file\n2 - add elements to file\n3 - show elements\n4 - put unique elements in another file\n5 - exit program\n");
scanf("%d",&r);
switch(r)
{
case 1 : n=create(); break;
case 2 : n=add(n); break;
case 3 : show(n); break;
case 4 : func(n); break;
case 5 : k=1; break;
default : printf("Command unrecognized!\n");
}
} while(k==0);
return 0;
}
EDIT:
function func() is the only problem.
EDIT: Yes I can run it under gdb.
EDIT:
sizeof(ELEM)=84 offsetof(ELEM,p)=80 in both cases.
Wow guys you will not guess this: aux.bin, actually anything aux.* is a reserved filename on Windows! That's why it is taking forever! Take a look here so you dont accidentally choose another reserved filename:
windows file name specification (search the page for 'aux')