#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
struct info
{
char name[15];
char surname[15];
char gender[15];
char education[15];
} sem;
FILE *fp=NULL;
int i, a;
char tmp[256] = {0x0};
while(1)
{
printf("Enter the value\n");
scanf("%d", &a);
if((fp = fopen("info.txt", "r")) != NULL)
{
switch(a)
{
case 0:
exit(0);
case 1:
for(i=0;!feof(fp);i++)
{
fscanf(fp, "%s %s %s %s", sem.name, sem.surname, sem.gender, sem.education);
printf("%s, %s, %s, %s\n",sem.name,sem.surname,sem.gender,sem.education);
}
break;
case 2:
while (fgets(tmp, sizeof(tmp), fp) != NULL)
{
if (strstr(tmp, "bachelors"))
{
/* Code works fine until this part */
fprintf(fp, "\n%s %s %s %s", sem.name, sem.surname, sem.gender, sem.education);
}
}
break;
default: printf("Default statement");
}
fclose(fp);
}
}
}
If anyone could point me out what im doing wrong, id be very greatful, I added a comment where code runs in to a problem and doesnt display anything. Basicly i have txt file. Program if user so desires needs to find lines in the file where "bachelor" is typed and give me back all of those lines.
You are opening your file in read mode (fp = fopen("info.txt", "r")) and trying to write in it using fprintf() which is not possible.
Use fp = fopen("info.txt", "r+") i.e read and write mode.
If you want to compare strings, you will have to use strcmp(), not an undefined function like "strstr". Also, strcmp returns 0 if two strings have same value. So you also have to check that the return value of strcmp() is zero or not.
Also as I replied to your question yesterday, fprintf() method appends the characters that you've passed as arguments to file. So, in your code, when you find string "bachelor", you just add same line at the end of the file. If you want to see those data in console, you can use printf() method.
Related
I a trying to take file name as argument and write strings using loop until user enter "-1".
problem 1: writing is not happening in text file and always shows empty
problem 2: cannot compare input -1 and "-1" . Always runs the else statements.
Note: I also tried fputs but it did not work that time either.
FILE *fp = fopen(argv[1], "a");
//fseek(fp, 0, SEEK_END);
char str[100];
printf("enter string\n");
bool flag = true;
while (flag == true) {
//printf("\nEnter data to append: ");
fflush(stdin);
fgets(str, 100, stdin);
if (strcmp(str, "-1") == 0) {
break;
} else {
fprintf(fp, "%s", str);
printf("Text written in file: %s\n", str);
}
}
fclose(fp);
Writing don't happen because of strcmp, I'm showing you my version of this with atoi.
#include <stdio.h>
#include <stdlib.h>
#define buffer 128
int main(int argc, char *argv[])
{
char str[buffer];
int flag = 1;
FILE *fp = fopen(argv[1], "w+"); //I prefer using write mode and not append
if(fp==NULL)
{
printf("Error opening file.\n"); //here you control if the file is opening correctly
exit(EXIT_FAILURE);
}
while(flag) //you don't need to write while(flag==true) (that's not wrong)
{
printf("Insert string: ");
scanf("%s", str);
if(atoi(str)==1) //the function strcmp as you wrote it will break after the
break; //first cicle, use atoi, it returns 1 if the string is a number
fprintf(fp, "%s\n", str); //the \n is to get the next string on the next row
}
fclose(fp);
return 0;
}
If you want to make it work with strcmp your if statement should be if(strcmp(str, "-1\n")) because fgets reads also the \n character.
Because fget() reads new line character.
So once you do comparation, It looks like:
strcmp("-1\n", "-1");
or
strcmp("-1\n\r", "-1");
You will never break the loop.
To remove newline character, let try:
strtok(str, "\n");
or
strtok(str, "\r\n");
I created a file and filled it with some entries. However, I want to read this file and show it on the screen. Also, after showing the entries, I want it to be deleted with my permission. But I am stuck at this point please help me.
EDIT: Code is updated but still couldn't figure it out how to do :/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char name[20], surname[20], city[30], country[30], gender[15];
int count = 0;
int main() {
FILE *f1;
f1 = fopen("C:\\FurkanArslan.txt", "r+");
while (count < 10) { // every step provides 5 new data, so 5*10 will provide 50 data in total.
printf("\n*Please enter required information: \n");
printf("Name :"); scanf("%s", name);
printf("Surname:"); scanf("%s", surname);
printf("Country:"); scanf("%s", country);
printf("City :"); scanf("%s", city);
printf("Gender :"); scanf("%s", gender);
fprintf(f1, " %s | %s | %s | %s | %s\n\n", name, surname, gender, city, country);
count++;
}
fclose(f1);
printf("\n<<<<<%d data has been successfully saved!>>>> \n", count * 5);
printf("-------------------------------------\n");
f1 = fopen("C:\\FurkanArslan.txt", "r");
char c, answer;
while ((c = fgetc(f1)) != EOF)
putchar(c); // In this part I displayed file on the screen.
printf("\n\n <<<< %d entries are displayed on the screen! >>>>", count * 5);
printf("\n\nWould you like to remove your file [Y/N] ?");
scanf(" %c", &answer);
if (answer == 'y' || answer == 'Y') {
remove("f1");
printf("\n\n***File successfully removed!");
}
return 0;
}
In order to show the content of a file you have to open it and read it letter by letter, after that, you can use the putchar function to output the current character
FILE *fp = fopen("path/to/file.txt","r");
char c;
while((c=fgetc(fp))!=EOF)
putchar(c);
fclose(fp);
after that to remove a file you need to use the remove function, which receives the name of the file as paramter.
remove("my_file.txt");
There are multiple issues in your code:
there is no need to make the variables and arrays global, just define them in the body of the main() function.
you should tell scanf() the maximum number of characters to store in the destination array with a length specifier in the format string (eg: "%19s") and check for conversion success.
the variable c used in the reading loop must have type int for proper detection of EOF. fgetc() returns a positive byte value if successful and the special negative value EOF at end of file.
you do not need to reopen the file after writing to it. Sine you opened it for update mode, you can just seek back to the beginning of the file with rewind(f1) or fseek(f1, 0L, SEEK_SET).
the file is open for read and update mode ("r+"): it will fail if the file does not exist. You should open it in write and update mode with "w+" to create or truncate it.
you should check that fopen succeeds at opening the file, otherwise you invoke undefined behavior passing a null stream pointer to fprintf.
to remove the file, remove() takes the filename as its argument. You must close the file before attempting to remove it.
Here is a modified version:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
const char *filename = "C:\\FurkanArslan.txt";
char name[20], surname[20], city[30], country[30], gender[15];
int count = 0;
FILE *f1 = fopen(filename, "w+");
if (f1 == NULL) {
printf("Cannot open file %s.\n", filename);
return 1;
}
while (count < 10) { // every step provides 5 new data, so 5*10 will provide 50 data in total.
printf("\n*Please enter required information: \n");
printf("Name :"); if (scanf("%19s", name) != 1) break;
printf("Surname:"); if (scanf("%19s", surname) != 1) break;
printf("Country:"); if (scanf("%29s", country) != 1) break;
printf("City :"); if (scanf("%29s", city) != 1) break;
printf("Gender :"); if (scanf("%14s", gender) != 1) break;
fprintf(f1, " %s | %s | %s | %s | %s\n\n", name, surname, gender, city, country);
count++;
}
printf("\n<<<<< %d data has been successfully saved to %s! >>>>\n",
count * 5, filename);
printf("-------------------------------------\n");
rewind(f1);
int c;
while ((c = fgetc(f1)) != EOF)
putchar(c);
printf("\n\n <<<< %d entries are displayed on the screen! >>>>\n", count);
fclose(f1);
printf("\nWould you like to remove your file [Y/N] ?");
char answer;
if (scanf(" %c", &answer) == 1 && (answer == 'y' || answer == 'Y')) {
if (remove(filename)) {
printf("\n\n***Error removing file %s: %s\n",
filename, strerror(errno));
} else {
printf("\n\n***File %s successfully removed!\n", filename);
}
}
return 0;
}
I am working on a program to write user input to a file and then search for a specific record in the file and output it to the screen.
I tried using fgets and also fputs but havent been successful
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main ()
{
FILE *fileptr;
char id [30];
char name [47];
char amt[50];
int i;
fileptr=fopen("C:\\Users\\Andrea\\Documents\\Tester.txt","w");
if (fileptr == NULL) {
printf("File couldn't be opened\n\a\a");
fclose(fileptr);
exit(0);
}
printf("Enter name: \n");
fscanf(fileptr,"%c",name);
fputs(name,fileptr);
fclose(fileptr);
printf("File write was successful\n");
return 0;
}
There are several problems.
You are trying to read from fileptr.
You are reading only one character, but treat the name array as if it was read in correctly.
A start would be:
[...]
printf("Enter name: \n");
if (fgets(name, sizeof name, stdin)) {
fputs(name,fileptr);
fclose(fileptr);
printf("File write was successful\n");
} else {
printf("Read error.\n");
}
But that's not all: you have forgotten to put error checking. E.g., how do you know that your "File write was successful\n" if you don't check at least the return value of fputs()?
I'm creating a program that asks the user to input a word. The word is then compared with a word in a text file. If correct, I want the user to input another word which should correspond with the next word in the text file and this should loop until the end of the file. I'm having trouble with the loop to the end of the file. Could someone please review my code and give me a few pointers? thanks so much
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
//Step 1: open file and declare variables//
FILE *fp;
fp = fopen("secretwords.txt","r");
char guess[20];
char secret[20];
int i, count;
//Step 2: Check that file opened correctly, terminate if not//
if (fp == NULL)
{
printf("Error reading file\n");
exit (0);
fclose(fp);
}
//Step 3: Create loop to run for each word to run to end of file//
fscanf(fp,"%s", secret);
//Need to create a loop here that will read the text file 20 times,
// each time reading the next word//
for (i=0; i < 3; i++)
{
printf("Please guess the word: \n");
scanf("%s", guess);
if (strcmp(secret,guess)==0)
{
printf("Your guess was correct\n");
return 0; //This return will terminate the program.
// I need to restart loop from here
}
else
{
printf("Your guess was incorrect. Please try again\n");
}
}
return 0;
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
FILE *fp = fopen("secretwords.txt", "r");
if (fp == NULL)
{
printf("Error reading file\n");
return 1;
}
char guess[20] = {0};
char secret[20] = {0};
while(fscanf(fp, "%s", secret) != EOF) // i would suggest you use 'fscanf_s("%s", guess);' instead if available
{
printf("Please guess the word: \n");
scanf("%s", guess); // i would suggest you use 'scanf_s("%s", guess);' instead if available
if (!strncmp(secret, guess, sizeof(guess)))
{
printf("Your guess was correct. Continue ...\n");
}
else
{
printf("Your guess was incorrect. Good bye.\n");
break;
}
}
fclose(fp);
return 0;
}
i made some suggestions about scanf_s and fscanf_s, if they are available, use them. But still, i am wondering why they are still teaching bad code in schools? I would not suggest to use *scanf* functions at all. Further reading: uncontrolled format string
Move the fscanf call that reads from the file to a function that returns the next word
loop for user input, only calling the function outlined above when you need to advance to the next word in the file (when the user inputs the correct thing)
I am working on a program to write user input to a file and then search for a specific record in the file and output it to the screen.
I tried using fgets and also fputs, but I haven't been successful. Here's what I have so far.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main ()
{
FILE *fileptr;
char id [30];
char name [47];
char amt[50];
fileptr = fopen("C:\\Users\\Andrea\\Documents\\Tester.txt", "w");
if (fileptr == NULL) {
printf("File couldn't be opened\n\a\a");
fclose(fileptr);
exit(0);
}
printf("Enter name: \n");
fscanf(fileptr, "%c", name);
fputs(name, fileptr);
fclose(fileptr);
printf("File write was successful\n");
return 0;
}
Use:
fscanf(stdin, "%s", name);
But better still, use scanf instead, as kol mentioned. This is because scanf() is designed to read the user response from the screen while fscanf() is for scanning from any input streams (which are usually files).
And the statement should be reading from the screen (stdin), not from the file (which was opened as "write" only).
Use scanf to read user input, and fprintf to write it to the file. Then use fscanf to read from the file, and printf to display what you have read. See cplusplus.com for the details and sample code.
EDIT:
Here is an example (please run the executable from the command line):
#include <stdio.h>
#include <string.h>
int main()
{
FILE *file;
int i;
char firstName[32];
char lastName[32];
int found = 0;
// Open the file for writing
file = fopen("records.txt", "wt");
if (!file)
{
printf("File could not be opened\n\a\a");
getchar();
return -1;
}
// Read and save data
for (i = 0; i < 3; ++i)
{
// Read data
printf("Record #%d\n", i + 1);
printf("Enter first name: "); scanf("%s", firstName);
printf("Enter last name: "); scanf("%s", lastName);
printf("\n");
// Save data
fprintf(file, "%s\t%s\n", firstName, lastName);
}
// Close the file
fclose(file);
// Open the file for reading
file = fopen("records.txt", "rt");
if (!file)
{
printf("File could not be opened\n\a\a");
return -1;
}
// Load and display data
i = 0;
while(!feof(file) && !found)
{
++i;
fscanf(file, "%s\t%s", firstName, lastName);
if (strcmp(firstName, "John") == 0 && strcmp(lastName, "Doe") == 0)
{
printf("Record found (#%d): %s %s\n", i, firstName, lastName);
found = 1;
}
}
if (!found)
printf("Record could not be found");
// Close the file
fclose(file);
return 0;
}