return string from function to main function - c

i have a text file named "name_file.txt" where all my file names is listed in. I'm calling new*data function with a file name. I have to check is the file name is already exists.in(namefile) if exists i have two option over write or making a new file name.if i choose new file name then it is calling the new_*data function . but when function returning the string it is the same string which i have called with not the new one..so I don't know how can i get the new string in main function?
#include<stdio.h>
#include<string.h>
char *new_data(char *str)
{
FILE *name_file, *data_file;
name_file=fopen("name_file.txt","a+");
char file_name[30];
char option;
char res[30];
while(!feof(name_file))
{
fscanf(name_file,"%s",file_name);
if(strcmp(file_name,str)==0)
{
break;
}
}
if(strcmp(file_name,str)==0)
{
printf("file is already exist over write [y n]: ");
scanf(" %c",&option);
if(option=='y')
{
data_file=fopen(str,"w");
fclose(data_file);
}
else
{
printf("Enter the file name: ");
scanf(" %s",&file_name);
strcpy(res,new_data(file_name));
}
}
else
{
data_file= fopen(str,"w");
fprintf(name_file,"%s\n",str);
fclose(data_file);
}
fclose(name_file);
return str;
}
int main(int argc, char **argv)
{
char res[20];
strcpy(res,new_data(argv[1]));
printf("%s",res);
return 0;
}

Related

can someone tell me why this code skips to the next input [duplicate]

This question already has answers here:
gets() does not work
(3 answers)
Why is gets() not consuming a full line of input?
(7 answers)
Closed 1 year ago.
I am trying to read students data (name, department, roll, sgpa, cgpa), I used fgets function to read name and department, but it skips to the department and can't read name.
here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char name[100];
char department[50];
int roll;
float sgpa[12];
float cgpa;
} Student;
void add(FILE *fp);
void modify(FILE *fp);
void display(FILE *fp);
FILE * del(FILE * fp);
int main(int argc, char **argv) {
int option;
FILE *fp;
fp = fopen("db.txt", "rb+");
if (fp == NULL) {
fp = fopen("db.txt", "wb+");
if (fp == NULL) {
printf("Can't open the database");
return 0;
}
}
printf("\t1. Add Student");
printf("\n\t2. Modify Student");
printf("\n\t3. Show All Student");
printf("\n\t4. Remove Student");
printf("\n\tEnter Your Option :--> ");
scanf("%d",&option);
switch(option)
{
case 1:
add(fp);
break;
case 2:
// modify(fp);
break;
case 3:
// display(fp);
break;
case 4:
// fp = del(fp);
break;
default:
printf("Unkonw option\n");
}
return 0;
}
void add(FILE *fp) {
Student std;
int i;
float cgpa;
fseek(fp,0,SEEK_END);
printf("\n\tEnter Full Name of Student: ");
fflush(stdin);
fgets(std.name,100,stdin);
std.name[strlen(std.name)-1]='\0';
printf("\n\tEnter Depertment Name: ");
fflush(stdin);
fgets(std.department,50,stdin);
std.department[strlen(std.department)-1]='\0';
printf("\n\tEnter Roll number: ");
scanf("%d",&std.roll);
printf("\n\tEnter SGPA for 12 semesters\n");
for(i=0,cgpa=0; i<12; i++)
{
scanf("%f",&std.sgpa[i]);
cgpa+=std.sgpa[i];
}
cgpa/=12.0;
std.cgpa=cgpa;
fwrite(&std,sizeof(std),1,fp);
}
Is there a way of limiting scanf in C?
I did this, if you're having that many problems with string input giving an eye on my other answer might help you
Here's a more specific answer to your problem on message you place what you wanna print before the input and StringInput you place the array you're using to hold the message
I hope this works since you also use a array for it
also i see this:
fp = fopen("db.txt", "rb+");
if (fp == NULL) {
fp = fopen("db.txt", "wb+");
if (fp == NULL) {
printf("Can't open the database");
return 0;
}
}
which may not be what you want because if it fails because of a sudden glitch by using wb+ you will overwrite it
“r+” – Searches file. Opens the file for both reading and writing. If opened successfully, fopen() loads it into memory and sets up a pointer which points to the first character in it. Returns NULL, if unable to open the file.
“w+” – Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file.
FUNCAUX_MAX_STRING is a macro and you define it like so:
#define FUNCAUX_MAX_STRING 100
This makes it so that the number or elements is 100 and you can easily change every number thats using the macro by simply changing the value once
void readString(char message[FUNCAUX_MAX_STRING], char StringInput[FUNCAUX_MAX_STRING], int maxChars)
{
int sizeString;
do // Repete leitura caso sejam obtidas strings vazias
{
printf("%s", message);
fgets(StringInput, maxChars, stdin);
sizeString = strlen(StringInput);
if (sizeString == 1)
{
printf("Nao foram introduzidos caracteres!!! . apenas carregou no ENTER \n\n");
}
}
while (sizeString == 1);
if(StringInput[sizeString-1] != '\n')
{
cleanBufferStdin();
}
else
{
StringInput[sizeString-1] = '\0';
}
}
void cleanBufferStdin(void)
{
char chr;
do
{
chr = getchar();
}
while (chr != '\n' && chr != EOF);
}

Command Flow in C, function call after printf

So I have this super simple C code here taking a user input and prints it out followed by a "T-Plus" while loop. In this case I chose a random name for testing "whoa", but the while loop is not called. My question is, why does the "T-Plus: %d\n" while loop print not be called after the printf() function?:
#include <stdio.h>
char getString();
void tcount(void);
int main(void)
{
tcount();
}
void tcount(void)
{
// class scanf user input
printf("%s", getString());
int i = 1;
do
{
printf("T-Plus: %d\n", i);
i++;
} while( i < 51 );
}
char getString()
{
char name;
printf("Please a string name: \n");
scanf("%s", &name);
return name;
}
Now when I run it, this becomes the output:
$ ./namecount
Please a string name:
whoa
but the T-Plus: string does not get called.
I see two issues here:
1) In function getString() you are trying to read/scan a string in a char, you need memory to store the string and a terminating char, so you can use either of these two ways
Use a char array e.g. char name[50]; or
Use a char pointer and
allocate memory using malloc e.g.
char *p_name = malloc(sizeof(char)*50);
2) You are then trying to return this string which is stored in local variable (which would get destroyed as soon as function ends) so you should use the second approach (use malloc) and return the pointer.
So your code would look like:
#include <stdio.h>
#include <stdlib.h>
char * getString();
void tcount(void);
int main(void)
{
tcount();
}
void tcount(void)
{
// class scanf user input
char *p_name = getString();
printf("%s", p_name);
free(p_name);
int i = 1;
do
{
printf("T-Plus: %d\n", i);
i++;
} while( i < 51 );
}
char *getString()
{
char *p_name = malloc(sizeof(char)*50);
printf("Please a string name: \n");
scanf("%s", p_name);
return p_name;
}
Above answer did not work, Okay so I've edited the code like this, it compiles fine. But raises a segmentation fault though.
#include <stdio.h>
#include <stdlib.h>
char * getString();
void tcount(void);
int main(void)
{
tcount();
}
void tcount(void)
{
// class scanf user input
char *name = getString();
printf("%s", name);
free(name);
int i = 1;
do
{
printf("T-Plus: %d\n", i);
i++;
} while( i < 51 );
}
char * getString()
{
char *p_name[50];
printf("Please a string name: \n");
scanf("%49s", (char *) &p_name);
return *p_name;
}
When the program is run, it asks for your input but still raises a Segmentation fault (core dumped).

c program function not working properly

#include<stdio.h>
#include<string.h>
void createIndexFile(char[]);
int main()
{
FILE *fp;
char fname[40];
int option;
printf("\nEnter the filename to open: ");
scanf("%s",fname);
fp=fopen(fname,"r");
if(fp==NULL)
{
printf("\nCannot open the file\n");
return 0;
}
else
{
printf("\n%s",fname);
createIndexFile(fname);
}
while(1)
{
printf("\n*****MENU*****\n");
printf("\n1.Display ......\n2.Insert new data\n3.Find data\n4.Display data\n5.Exit\n");
printf("\nChoose an operation: ");
scanf("%d",&option);
switch(option)
{
case 1: break;
case 2: break;
case 3: break;
case 4: break;
case 5: return 0;
default: printf("\nInvalid selection\n");
}
}
}
void createIndexFile(char fname[])
{
int i=0;
char tempFile[40];
char indexFile[40];
printf("\n%s",fname);
strcpy(indexFile,"xyz");
strcpy(tempFile,fname);
while(tempFile[i]!='.')
{
if(tempFile[i]=='/')
tempFile[i]='_';
}
strcat(tempFile,".idx");
strcat(indexFile,tempFile);
printf("\nIndex File Name: %s",indexFile);
}
It is a program where after a filename is entered suppose /home/abc.txt and my name is xyz then an index file should be created xyz_home_abc.idx.
After the filename is entered and if it is present, it should go to else part and function
createIndexFile(fname);
should be called. But inside the function, nothing is working properly. If we print a character or something, it is printed. But if I try to give another printf it is not working.
Corrected your function
void createIndexFile(char fname[])
{
int i=0;
char tempFile[40];
char indexFile[40];
printf("\n%s",fname);
strcpy(indexFile,"");
while(fname[i]!='.')
{
if(fname[i]=='/')
tempFile[i]='_';
else
tempFile[i]=fname[i];
i++;
}
tempFile[i]='\0';
strcat(tempFile,".idx");
strcat(indexFile,tempFile);
printf("\nIndex File Name: %s",indexFile);
}

Why does my append function no longer write to file

I'm writing a code for a simple phone book. Everything works fine except that after successfully deleting an entry using my delete function my append function cant seem to write entries to the file anymore. unless I delete the database.data file that I'm using to store the entries.
NOTE:
the character array file="database.data"
delete function:
void deletee()
{
int tode,count;
char ch;
printc();
count=1;
FILE *filepointer,*filepointer2;
filepointer=fopen(file,"r+");
filepointer2=fopen("datatemp.data","w+");
if(filepointer==NULL)
{
printf("ERROR ERROR!");
}
printf("Enter line number of the line to be deleted: \n");
scanf("%d",&tode);
while (ch!=EOF)
{
ch=getc(filepointer);
if(ch=='\n')
{
count++;
}
if(count!=tode)
{
fprintf(filepointer2,"%c",ch);
}
}
fclose(filepointer);
fclose(filepointer2);
remove(file);
rename("datatemp.data",file);
printf("Content successfully deleted!!");
}
heres the function for append:
void append(struct entry *ptr)
{
FILE *filepointer;
filepointer=fopen(file,"a+");
fflush(stdin); //This block is asking for the inputs to be placed into the file
printf("Enter FName: ");
scanf("%s",&ptr->fn);
printf("\nEnter LName: ");
scanf("%s",&ptr->ln);
printf("\nEnter MName: ");
scanf("%s",&ptr->mn);
printf("\nEnter BD: ");
scanf("%s",&ptr->bd);
printf("\nEnter CNum: ");
scanf("%s",&ptr->cn);
if(filepointer==NULL)
{
printf("The file does not exist.\n");
return;
}
system("cls");
fprintf(filepointer,"%15s%15s%15s%9s%11s\n",ptr->fn,ptr->ln,ptr->mn,ptr->bd,ptr->cn);
fclose(filepointer);
printf("Entries successfully written!\n");
}
struct entry
{
char fn[15];
char ln[15];
char mn[15];
char bd[9];
char cn[11];
}p;
if you want more details please do tell me.
UPDATE-
I narrowed down the problem to the while loop in the delete function my append function seems to work after using delete if the contents in the while loop were written like this:
while (ch!=EOF)
{
ch=getc(filepointer);
if(count!=tode)
{
fprintf(filepointer2,"%c",ch);
if(ch=='\n')
{
count++;
}
}
}
But if the while loop were written in this way it would delete all the entries following the specified line. whereas in my previous code for the while loop in the deletee function it only deletes that specific line, but as stated the problem of the append function not being able to write to the file will persist until I delete the file "database.data" manually.
Solved the problem turns out that the append function was able to write entries into the file the only problem is my print function couldnt print out the new entries due to the delete function leaving garbage after being executed. revised the code so that no garbage would be written after deleting.
void deletee()
{
int tode,count;
char ch,sc;
printc();
count=1;
FILE *filepointer,*filepointer2;
filepointer=fopen(file,"r+");
filepointer2=fopen("datatemp.data","w+");
if(filepointer==NULL)
{
printf("ERROR ERROR!");
}
printf("Enter line number of the line to be deleted: \n");
scanf("%d",&tode);
while (ch!=EOF)
{
ch=getc(filepointer);
if(count!=tode)
{
if(ch==EOF)
{
break;
}
fprintf(filepointer2,"%c",ch);
}
if(ch=='\n')
{
count++;
}
}
fclose(filepointer);
fclose(filepointer2);
swap();
remove("datatemp.data");
printf("Content successfully deleted!!");
}

Load data from file in C

I'm creating a simple C program - employee database... My data are stored in a .txt file, separated by commas and \n, so it looks like this:
data1,id1,name1
data2,id2,name2
What is the best way (in C, not C++) to load all data from the file and every value save as independent variable (e.g. p->data, p->id, p->name)?
This is the code I use to store data into variables (not into the file, variables just for the script):
void insert(emp *p,int n)
{
p=p+n;
printf("\nenter name of emplyee:");
_flushall();
gets(p->name);
printf("\nenter employee id:");
scanf("%d",&p->empid);
printf("\nenter salary of the emplyee:");
scanf("%d",&p->salary);
printf("\nenter phone no of the emplyee:");
flushall();
gets(p->ph);
}
And this script saves data to a file:
void sejv(emp *p,int n)
{
int i;
FILE *fptr;
fptr=fopen("ulozka.txt","w+");
if(fptr==NULL){
printf("Error opening file!");
getchar();
}
printf("Ukladani...");
for(i=0;i<n;i++)
{
fprintf(fptr,"%d,%s,%d,%s\n",p->empid,p->name,p->salary,p->ph);
p=p+1;
}
fclose(fptr);
exit(0);
}
All I need is to load the data to the main function so I can work with it.
EDIT:
I'm adding the rest of my code:
typedef struct employee
{
char name[20],ph[20];
int empid,salary;
}emp;
void main()
{
emp e;
emp *p;
int n=0,ch;
p=&e;
}
And "something" from the function I need to create...
void nacti(emp *p,int n)
{
int i;
FILE *fptr;
fptr=fopen("ulozka.txt","r");
if(fptr==NULL){
printf("Error opening file!");
getchar();
}
printf("Nacitani...");
//loading function
p=p+n;
fscanf(fptr,"%d,%[^\,],%d,%s", &p->empid, p->name, &p->salary,p->ph);
printf("%s", p->name);
}
I need a function that would read the data from the txt file by collumns and rows (a loop that would add the data from the first row to a p, then increase the value of p by 1, insert data from the second row and so on...)
Thank you for any advice...
Check the below code it can be done ad shown below:
struct data
{
int index;
int id;
char name[30];
};
int main ()
{
struct data p[3];
int i=0;
FILE *fp = fopen("input.txt","r+");
while(fscanf(fp,"%d,%d,%s",&p[i].index,&p[i].id,p[i].name) != EOF)
{
i++;
}
i=0;
while(i<3)
{
fprintf(fp,"%d %d %s\n",p[i].index,p[i].id,p[i].name);
i++;
}
fclose(fp);
}

Resources