How to give access to text file using if statement? - c

I am trying to give an if statement to check if a particular name is present in text file, then give access to it otherwise give error message.
#include <stdio.h>
#include <stdlib.h>
int main(){
printf("For person details, please enter the person name: \n");
FILE * fr = fopen("/home/bilal/Documents/file.txt","r");
int catch, i=0, index=0;
char ch[100];
printf("Enter your Name: ");
if (scanf("%s", )){ // Don't know what to put here?
perror("Error while reading!");
return 0;
}
catch = fgetc(fr);
while(catch != EOF){
ch[index] = catch;
if (ch[index] == ' '){
ch[index] = '\0';
printf("Here is your result: %s\n",ch);
index = 0;
i++;
}
else
index++;
catch = fgetc(fr);
}
fclose(fr);
return 0;
}

Simply the program firstly opens a file and asks for a user input and verifies if the provided content is case-sensitively matched with the file. If so, then it'll let the program access the entire file and display on the screen, to do that, we must use another FILE b/c the old *fp is already manipulated and in case it's reused, it may display wrong data.
#include <stdio.h>
#include <string.h>
int main(void) {
FILE *fp = fopen("file.txt", "r"); // for verification
FILE *fp1 = fopen("file.txt", "r"); // for future use
char ch[50], str[50];
short int FLAG = 0;
printf("Enter the string: ");
scanf("%s", &str); // asks for input
while (fscanf(fp, "%s", ch) != EOF) {
if (!strcmp(ch, str)) { // checks if a string matches provided by the user
printf("Found! Here's your details...\n\n");
FLAG = 1;
}
}
if (!FLAG == 1) { // no? exits.
printf("Not found, access denied!\n");
return -1;
}
fclose(fp);
int c = fgetc(fp1); // yes? let's go...
while (c != EOF) {
printf("%c", c); // displays containing data
c = fgetc(fp1);
}
fclose(fp1);
return 0;
}

You'll want to add a variable for your scanf output:
char name[100];
if (scanf("%s", name) != -1)
// ...
Then to compare both you'll use strcmp.
#include <string.h>
//...
if (strcmp(ch, name) == 0)
// both are equal
Note that you can access documentation for scanf and strcmp by typing man scanf or man strcmp in your terminal.

int main()
{
printf("For person details, please enter the person name and id card
number: \n");
printf("Enter your Name: ");
char personName[100];
scanf("%s", personName);
printf("Enter your card number: ");
int cardNumber;
if (scanf("%d", &cardNumber)){
printf("no error detected");
}
else{
printf("error while reading");
}
return 0;
}

The fixed code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
printf("For person details, please enter the person name: \n");
FILE* fr = fopen("/home/bilal/Documents/file.txt", "r");
int catch, i = 0, index = 0;
char ch[100] = { 0 };
if (fr == NULL)
{
perror("Invalid file opening!");
return 1;
}
printf("Enter your Name: ");
fgets(ch, 100, fr);
size_t len = strcspn(ch, "\n");
ch[(len < 100) ? (len) : (99)] = 0; // For file safety checking
if (strlen(ch)) { // Don't know what to put here?
perror("Error while reading!");
return 1;
}
catch = fgetc(fr);
while (catch != EOF) {
ch[index] = catch;
if (ch[index] == ' ') {
ch[index] = '\0';
printf("Here is your result: %s\n", ch);
index = 0;
memset(ch, 0, 100);
i++;
}
else
{
index++;
}
catch = fgetc(fr);
}
fclose(fr);
return 0;
}

Related

Not Getting Output in File

#include <stdio.h>
int main()
{
FILE *f1;
int ch, i, n = 0;
char q[500], opt[4][100];
int corAns;
f1 = fopen("C://Users//Lenovo//Desktop//fileInC1.txt", "a+");
if (f1 == NULL)
{
printf("Error Opening File.");
return 0;
}
else
{
while (n != 2)
{
n++;
printf("\nQuestion: ");
fgets(q, 500, stdin);
for (i = 0; i < 4; i++)
{
printf("\nOption %d: ", i + 1);
fgets(opt[i], 100, stdin);
}
printf("\nCorrect answer: ");
scanf("%d", corAns);
//program terminating here after only one iteration
fprintf(f1, "{\nQ: \"%s\", \n\topt: [\"%s\", \"%s\", \"%s\", \"%s\"], \n\tCA: %d }", q, opt[0], opt[1], opt[2], opt[3], corAns);
printf("\nData Written Successfully.");
}
}
fclose(f1);
return 0;
}
I have been trying to create a Javascript generator as you can see in the code.
The main problem i am getting is inside the while loop.
The while loop is terminating after only one iteration and the program not writting the data in the created file. The file already exists.
I am not getting where is the problem occuring.
You need to cleanse your input of new-lines. You also had a redundant Else statement, and Scanf requires the address of a variable, not it's value.
This should work for you. You can check out this question here: Fgets skipping inputs, which I shamelessly copied.
#include <stdio.h>
#include <string.h>
int main()
{
FILE *f1;
int ch, i, n = 0;
char q[500], opt[4][100];
int corAns;
int c;
char *p;
f1 = fopen("fileInC1.txt", "a+");
if (f1 == NULL)
{
printf("Error Opening File.");
return 0;
}
while (n != 2)
{
n++;
printf("\nQuestion: ");
fgets(q, 500, stdin);
if ((p=strchr(q, '\n')) != NULL) *p = '\0';
for (i = 0; i < 4; i++)
{
printf("\nOption %d: ", i + 1);
fgets(opt[i], 100, stdin);
if ((p=strchr(opt[i], '\n')) != NULL) *p = '\0';
}
printf("\nCorrect answer: ");
scanf("%d", &corAns);
//program terminating here after only one iteration
fprintf(f1, "{\nQ: \"%s\", \n\topt: [\"%s\", \"%s\", \"%s\", \"%s\"], \n\tCA: %d }", q, opt[0], opt[1], opt[2], opt[3], corAns);
printf("\nData Written Successfully.");
while ( (c = getchar()) != '\n' && c != EOF );
}
fclose(f1);
return 0;
}

C program to print line number in which given string exists in a text file

I have written a C program that opens a text file and compares the given string with the string present in the file. I'm trying to print the line number in which the same string occurs, but I am unable to get the proper output: output does not print the correct line number.
I would appreciate any help anyone can offer, Thank you!
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main() {
int num = 0, line_number = 1;
char string[50];
char student[100] = { 0 }, chr;
while (student[0] != '0') {
FILE *in_file = fopen("student.txt", "r");
if (in_file == NULL) {
printf("Error file missing\n");
exit(1);
}
printf("please enter a word \n");
scanf("%s", student);
while (fscanf(in_file, "%s", string) == 1) {
if (chr == '\n') {
if (strstr(string, student) == 0) {
break;
} else
line_number += 1;
}
}
printf("line number is: %d\n", line_number);
fclose(in_file);
}
return 0;
}
You cannot read lines with while (fscanf(in_file, "%s", string), the newlines will be consumed by fscanf() preventing you from counting them.
Here is an alternative using fgets():
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char string[200];
char student[100];
int num = 0, line_number = 1;
FILE *in_file = fopen("student.txt", "r");
if (in_file == NULL) {
printf("Error file missing\n");
exit(1);
}
printf("please enter a word \n");
if (scanf("%s", student) != 1) {
printf("No input\n");
exit(1);
}
while (fgets(string, sizeof string, in_file)) {
if (strstr(string, student)) {
printf("line number is: %d\n", line_number);
}
if (strchr(string, '\n')) {
line_number += 1;
}
fclose(in_file);
}
return 0;
}

how to stop a while loop to enter, in the same variable

I have to enter random names and weights and finish the loop when I hit enter instead of the name. However the way I used to detect the enter does not serve to take the name so getting two variables. The question is how to put the enter of the test and name using the same variable
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
int c, weight[1000], i = 0;
char name[1000];
puts ("Enter the person's name or only enter to end the program");
if ((c = getchar() == '\n')) {
} else {
while (c != '\n') {
printf("Enter the name");
scanf("%s", &nome[i]);
i++;
printf("Enter the \n");
scanf("%i", &weight[i]);
}
}
return 0;
}
Here is a simple example
#include <stdio.h>
#include <string.h>
int main(void)
{
char name[1000] = {0}; // initialise
puts ("Enter the person's name or only enter to end the program");
if (fgets(name, sizeof(name), stdin) != NULL) {
name [ strcspn(name, "\r\n") ] = 0; // remove trailing newline etc
if (strlen(name)) {
printf("The name entered was: %s\n", name);
}
else {
printf("You did not enter a name\n");
}
}
return 0;
}
First off, names is an array of characters and you're treating it like an array of strings. Secondly, loops that need to exit based on input are most clearly expressed with break:
char *names[1000];
int count = 0;
while (1) {
char *r, buf[1000];
int len;
char *r = fgets(buf, 1000, stdin);
if (NULL == r) break; // EOF
if ((len = strlen(buf)) < 2) break; // NL only
r = malloc(len + 1);
if (NULL == r) break;
strcpy(r, buf);
names[count] = r;
count += 1;
...
}
...

File does not fprint correctly in C?

So here I have a basic program that will write to a specific line in a file by writing the contents of the file into a temporary file where the new line is written and then the contents of that file is then copied back into the starting file.
(Scores) = File
(Sub) = Temp
#include <stdio.h>
#include <conio.h>
#include <string.h>
void insert(void);
int main()
{
insert();
}
void insert(void)
{
FILE *fp,*fc;
int lineNum;
int count=0;
char ch=0;
int edited=0;
int score=0;
fp=fopen("Test 02 Scores.txt","r");
fc=fopen("Sub.txt","w");
if(fp==NULL||fc==NULL)
{
printf("\nError...cannot open/create files");
exit(1);
}
printf("Enter the score");
scanf("%d",&score);
printf("\nEnter Line Number Which You Want 2 edit: ");
scanf("%d",&lineNum);
while((ch=fgetc(fp))!=EOF)
{
if(ch=='\n')
count++;
if(count==lineNum-1 && edited==0)
{
if(lineNum==1)
{
fprintf(fc,"%d\n",score);
}
else
fprintf(fc,"\n%d\n",score);
edited=1;
while( (ch=fgetc(fp))!=EOF )
{
if(ch=='\n')
break;
}
}
else
fprintf(fc,"%d",ch);
}
fclose(fp);
fclose(fc);
if(edited==1)
{
printf("\nLine has been written successfully.");
char ch;
FILE *fs, *ft;
fs = fopen("Sub.txt", "r");
if( fs == NULL )
{
printf("File is not real");
exit(1);
}
ft = fopen("Test 02 Scores.txt", "w");
if( ft == NULL )
{
fclose(fs);
printf("File is not real\n");
exit(1);
}
while( ( ch = fgetc(fs) ) != EOF )
fputc(ch,ft);
printf("\nFile copied\n");
getch();
fclose(fs);
fclose(ft);
}
else
printf("\nLine Not Found");
}
However, a problem has arisen, I started to write this code for use with strings, but since decided to use number values, whenever I try to copy with the integer values the program will not copy anything right, I Know this may be caused by the char to int but I'd rather have more help in assessing where I should change stuff.
The error is in this line
fprintf(fc,"%d",ch)
%d prints ch as an integer, not as a character, you should instead write
fprintf(fc,"%c",ch)
or use fputc()
There are some small issues with your code, here is a working version. I added comments where I changed things.
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h> // needed for exit()
void insert(void);
int main()
{
insert();
}
// use fgets to read from keyboard, it is simpler.
int readNumber()
{
char buffer[64] = {0};
fgets(buffer, sizeof(buffer), stdin);
return atoi(buffer);
}
void insert(void)
{
FILE *fp = NULL; // prefer one decl per row
FILE *fc = NULL;
int lineNum = 0;
int count=0;
int ch=0; // should be int ch=0;
int edited=0;
int score=0;
// file names
const char src[] = "Test 02 Scores.txt";
const char dest[] = "Sub.txt";
fp=fopen(src,"r");
if(fp==NULL)
{
perror(src); // use perror() instead for better error msg
exit(EXIT_FAILURE); // there are std constants for exit args
}
fc=fopen(dest,"w");
if(fc==NULL)
{
perror(dest);
exit(EXIT_FAILURE);
}
printf("Enter the score: ");
score = readNumber(); // using fgets to avoid lingering \n in buffer
printf("\nEnter Line Number Which You Want 2 edit: ");
lineNum = readNumber();
while((ch=fgetc(fp))!=EOF) // fgetc returns int so ch should be int
{
if(ch=='\n') // better to have {} here too
{
count++;
}
if(count==lineNum-1 && edited==0)
{
if(lineNum==1)
{
fprintf(fc,"%d\n",score);
}
else // better to { } here too
{
fprintf(fc,"\n%d\n",score);
}
edited=1;
// i guess you want to remove old score
while( (ch=fgetc(fp))!=EOF )
{
if(ch=='\n')
{
break;
}
}
}
else // {} for avoiding future pitfall
{
fputc(ch,fc);
}
}
fclose(fp);
fclose(fc);
if(edited==1)
{
puts("\nLine has been written successfully."); // puts() when u can
int ch = 0; // int
FILE *fs = NULL;
FILE *ft = NULL;
fs = fopen(dest, "r");
if( fs == NULL )
{
perror(dest);
exit(EXIT_FAILURE);
}
ft = fopen(src, "w");
if( ft == NULL )
{
perror(src);
exit(EXIT_FAILURE); // at program exit files will close anyway
}
while( ( ch = fgetc(fs) ) != EOF )
{
fputc(ch,ft);
}
fclose(fs);
fclose(ft);
printf("\nFile copied\n");
getch();
}
else
{
printf("\nLine Not Found");
}
}

(C code) how would I pass my global variables between functions and return them when the main function needs them also?

(C code) how would I pass my global variables between functions and return them when the main function needs them also? I've posted my code below for reference. Of course, I also have a header file with my function prototypes in it as well but they only list variable types inside the closed brackets, not the variable names...
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include "myheader.h"
char user_filename[150];
char user_filename2[150];
FILE *fp;
FILE *fp2;
int num_shift;
int main()
{
int choice; // main variables
int option;
char result;
char ch;
int offset;
char character;
int tmp;
option = 0;
num_shift = 0;
strncpy(user_filename, "not set", sizeof("not set"));
strncpy(user_filename2, "not set", sizeof("not set"));
fp = NULL;
fp2 = NULL;
choice = menu(num_shift, user_filename, option); // get user's first selection
while(choice != QUIT) //execute so long as choice is not equal to QUIT
{
switch(choice)
{
case INPUT_FILE:
input(user_filename);
break;
case OUTPUT_FILE:
output();
break;
case NUM_TO_SHIFT:
num_shift = shift(num_shift);
printf ("Shift by %d\n",num_shift);
break;
case ENCODE:
encode(result, ch, num_shift, character);
break;
case QUIT:
quit();
break;
case REVIEW:
review (user_filename);
break;
default:
printf("Oops! An invalid choice slipped through. ");
printf("Please try again.\n");
}
choice = menu(num_shift, user_filename, 0); /* get user's subsequent selections */
}
quit();
}
int menu(int num_shift, char * user_filename, int option)
{
printf("\nText Encoder Service\n\n");
printf("1.\tEnter name of input file (currently '%s')\n", user_filename);
printf("2.\tEnter name of output file (currently '%s')\n", user_filename2);
printf("3.\tEnter number of characters data should be shifted (currently %d)\n", num_shift);
printf("4.\tEncode the text\n");
printf("5.\tReview the text in the input file\n");
printf("\n0.\tQuit\n\n");
printf("Make your selection: \n");
while( (scanf(" %d", &option) != 1) /* non-numeric input */
|| (option < 0) /* number too small */
|| (option > 5)) /* number too large */
{
fflush(stdin); /* clear bad data from buffer */
printf("That selection isn't valid. Please try again.\n\n");
printf("Your choice? ");
}
printf("Selecting %d\n\n", option);
return option;
}
int input(char * user_filename)
{
printf("Enter the filename of the file to encode:\n");
printf("(hit the Enter key when done)\n");
scanf("%s", user_filename);
printf("Getting %s\n\n", user_filename);
fp = fopen (user_filename, "r");
if (fp == NULL)
{
printf("\nSorry, I'm unable to open the file (%s) for reading\n", user_filename);
printf("Please try again.\n");
}
else
{
fclose(fp);
}
return INPUT_FILE;
}
int output()
{
printf("Enter the filename of the output file to store encoded information:\n");
printf("(hit the Enter key when done)\n");
scanf("%s", user_filename2);
printf("Opening File for Writing %s\n\n", user_filename2);
fp2 = fopen (user_filename2, "w");
if (fp2 == NULL)
{
printf("\nSorry, I'm unable to open the file (%s) for writing\n", user_filename2);
printf("Please try again.\n");
} else
{
fclose(fp2);
}
//return user_filename;
return INPUT_FILE;
}
int shift(int num_shift)
{
printf("Enter the number of letters to shift for each character: \n");
printf("(hit the Enter key when done)\n");
scanf("%d", &num_shift);
printf("Setting shift value to: %d\n\n", num_shift);
return num_shift;
}
int encode(char result, char ch, int offset, char character2)
{
int character;
printf("starting encoding with offset of %d\n", offset);
fp = fopen(user_filename, "r");
fp2 = fopen(user_filename2, "w+bc");
if ((fp == NULL) || (fp2 == NULL))
{
printf ("File not found\n");
return (0);
}
fseek(fp, 0, SEEK_SET);
printf("staring Encoding from %s to %s at position %ld\n", user_filename, user_filename2, ftell(fp));
int i = 0;
while(character = fgetc(fp))
{
if ( character == EOF)
{
//printf("%c",character);
//fprintf(fp2,"%c",result);
fclose(fp);
fflush(fp2);
fclose(fp2);
return(0);
}
if (isalpha (character))
{
if (character >= 'a' && character <= 'z')
{
result = character - 'a';
result = (result + offset) % 26; // 26 letters in the alphabet
result += 'a';
if (result < 'a')
{
result = 'z' - ('a' - result)+1;
}
} else if (character >= 'A' && character <= 'Z')
{
result = character - 'A';
result = (result + offset) % 26; // 26 letters in the alphabet
result += 'A';
if (result < 'A')
{
result = 'Z' - ('A' - result)+1;
}
}
//printf("(%c)",result);
} else
{
result = character;
//printf("(%x)", result);
}
printf("%c",result);
fprintf(fp2,"%c",result);
}
return 0;
}
void quit()
{
//fclose(fp);
//fclose(fp2);
printf("Quiting...Bye!");
printf("\n");
exit(0);
}
int review(char * user_filename)
{
char character;
fp = fopen(user_filename, "r");
printf("Showing text from %s file\n", user_filename);
printf("----------BEGIN OF TEXT--------------\n");
while(character = fgetc(fp))
{
if ( character == EOF)
{
printf("%c",character);
printf("\n----------END OF TEXT--------------\n");
fclose(fp);
return(0);
}
printf("%c",character);
}
}
You don't need to pass them around as parameters, you can just access them from anywhere (hence global, well as long as you can see the variable).
Any modifications made to those variables are visible to everyone (aside from multithreading issues) so you have no trouble using them in your functions and in main as well.
You do not need to pass global variables because global variables have global scope, that is they can be accessed anywhere. This is VERY BAD programming practice because it may introduce side-effects later in the program when you decide to use the same name for another purpose for example.
See wikipedia for details.

Resources