Read from file in C and execute conditional logic - c

I am new to programming and have a few questions as to how to implement this idea.
I am looking to have a user enter their name/string of digits and if their name is on a list, to then execute a string of commands. I am not to sure how to impliment this, but with some gogle-ing I was able to come up with this code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char userName[10];
printf("\n\n\n\nPlease enter your name: ");
scanf_s("%s",userName); // userName should be verified/found inside the results.dat file
FILE *fp;
fp = fopen("results.dat", "r");
if (fp == NULL) {
printf("I couldn't open results.dat for writing.\n");
exit(0);
}
if (fp == John) {
//Dispence squence of pills for John
}
if (fp == Mary) {
//Dispence squence of pills for Mary
}
return 0;
}
I do not think I am using the if statement correctly. how can I do something like:
if (content in fp == john, execute/call another function)
Thanks in advance!

Try this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char userName[10];
char names[20];
printf("\n\n\n\nPlease enter your name: ");
scanf("%s",userName); // userName should be verified/found inside the results.dat file
FILE *fp;
fp = fopen("results.dat", "r");
if (fp == NULL) {
printf("I couldn't open results.dat for writing.\n");
exit(0);
}
while(fgets(names, 20, fp)) // fgets reads a line from the file
{
names[strlen(names)-1] = '\0'; // but it leaves the newline character "\n" , so the strings won't match
if(strcmp(names, userName) == 0) // if the value returned by strcmp is zero then string match
{
printf("Match found\n");
}
}
return 0;
}

fopen simply opens a file for reading and/or writing, to read the actual content of the file you need to use functions such as fgets, fscanf and so on.
Short example
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char* argv[])
{
char name[64];
char buffer[64];
printf ("Please enter your name: ");
file = fopen ("results.dat", "rw");
if (!file) {
printf ("Results.dat could not be opened.\n");
exit(-1);
}
if ( fgets (buffer, 64, file)) {
if (strcmp (buffer, "john")) {
printf ("Contents of file is john\n");
}
}
return 0;
}

Related

how to append the date in the existing file?

#include<stdio.h>
#include<stdlib.h>
void main(){
FILE *fp;
char str[20];
fp=fopen("krishna.txt","a");
if(fp==NULL)
printf("File not exist");
exit(1);
printf("Enter the strings:");
gets(str);
fputs(str,fp);
//fprintf(fp,"%s",str);
printf("Successfully print");
fclose(fp);
}
why it is not appending
i want this to append in my existing file name krishna
Use curly braces { } to surround multiple statements in a block.
Additionally, try using perror to better understand why things fail.
Do not use gets, please read: Why is the gets function so dangerous that it should not be used?
Use a proper signature for main: void main() is rarely correct. Use either int main(int argc, char **argv) if you want to use program arguments, or int main(void) if you do not.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char str[128];
FILE *fp = fopen("krishna.txt", "a");
if (!fp) {
perror("fopen");
exit(EXIT_FAILURE);
}
printf("Enter a line of text: ");
if (fgets(str, sizeof str, stdin) && fputs(str, fp) > 0) {
puts("Line appended to file.");
} else {
perror("fgets/fputs");
}
fclose(fp);
}

How to scan a string and write it in a file?

I want to scan a string that a user inputs, then write it into the file (file.txt), but this doesn't seem to work for some reason
int main()
{
FILE *stream;
stream = fopen("file.txt", "w");
char str[] = { '\0 ' };
scanf("%s", &str);
fprintf(stream, "%s.\n", str);
fclose(stream);
return(0);
}
try this, should work just fine.
It did for me so it should for you too.
#include <stdio.h>
#include <string.h>
int main()
{
FILE *stream;
stream = fopen("ceva.txt", "w");
if (stream == NULL) {
perror("Failed: ");
return 1;
}
char str[250];
scanf("%249s", str);
fprintf(stream, "%s.\n", str);
fclose(stream);
return 0;}
You must change scanf with fscanf

C. Can't open a text file with fopen on Windows Vista

I wanted to learn how to use getc function in C so I wrote a little program that is supposed to give the first letter of a text file as an output.
Here's how it looks:
int main()
{
int character;
FILE *file;
file = fopen("file.txt", "r");
if(file == NULL)
printf("can't open\n");
character = getc(file);
printf("%c", character);
fclose(file);
return 0;
}
It fails to open the file.txt file and I can't figure out why. file.txt is in the same folder as my program's .exe file. I'm using Windows Vista.
Thanks in advance
This extracts the program's location from argv[0]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MYFILE "plik.txt"
int main(int argc, char *argv[]) {
char fname[_MAX_PATH+1];
int znak;
FILE *plik;
char *ptr;
strcpy(fname, argv[0]);
ptr = strrchr(fname, '\\');
if(ptr == NULL) {
strcpy(fname, MYFILE);
}
else {
strcpy(ptr+1, MYFILE);
}
plik = fopen(fname, "r");
if(plik == NULL) {
printf("Can't open %s\n", fname);
}
else {
znak = getc(plik);
printf("First char of %s is %c\n", fname, znak);
fclose(plik);
}
getchar();
return 0;
}
Try
if (plik == NULL) { perror("plik.txt"); exit(EXIT_FAILURE); }
for a better understanding of the cause of error.

File manipulations in C

I am using a simple 'C' code to do the following:
1) Read from a .txt file.
2) Based on the string present in the .txt file, a directory will be created.
I am not able to perform step-2, as I am not clear with type conversions.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <direct.h>
int main()
{
char ch, file_name[25];
FILE *fp;
//printf("Enter the name of file you wish to see\n");
//gets(file_name);
fp = fopen("input.txt","r"); // read mode
if( fp == NULL )
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
printf("The contents of %s file are :\n", file_name);
while( ( ch = fgetc(fp) ) != EOF )
printf("%c",ch);
if( _mkdir(ch ) == 0 )
{
printf( "Directory successfully created\n" );
printf("\n");
}
fclose(fp);
return 0;
}
Here is the error:
*error #2140: Type error in argument 1 to '_mkdir'; expected 'const char *' but found 'char'.*
YES, compiler is right.
You are passing a char c to _mkdir, instead of a string.
You should read the string from file and store it to file_name (I guess you forget) and then
_mkdir(file_name);
See below:
#include <stdio.h>
#include <stdlib.h>
#include <direct.h>
int main()
{
char file_name[25];
FILE *fp;
fp = fopen("input.txt", "r"); // read mode
if (fp == NULL)
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
fgets(file_name, 25, fp);
_mkdir(file_name);
fclose(fp);
return 0;
}
It's because you only have a single char (the c in fgetc stands for char) while _mkdir wants a string (i.e. char *).
You should probably use fgets instead to read the input.
If you dont want to use fgets , then you can use this.
#include <stdio.h>
#include <stdlib.h>
#include <direct.h>
int main()
{
char file_name[25];
String str;
FILE *fp;
char ch;
int i=0;
fp = fopen("input.txt", "r"); // read mode
if (fp == NULL)
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
while( ( ch = fgetc(fp) ) != EOF ){
printf("%c",ch);
file_name[i];
i++
}
str=file_name;
_mkdir(str);
fclose(fp);
return 0;
}

reading a string from a file

I have one text file. I have to read one string from the text file. I am using c code. can any body help ?
Use fgets to read string from files in C.
Something like:
#include <stdio.h>
#define BUZZ_SIZE 1024
int main(int argc, char **argv)
{
char buff[BUZZ_SIZE];
FILE *f = fopen("f.txt", "r");
fgets(buff, BUZZ_SIZE, f);
printf("String read: %s\n", buff);
fclose(f);
return 0;
}
Security checks avoided for simplicity.
This should work, it will read a whole line (it's not quite clear what you mean by "string"):
#include <stdio.h>
#include <stdlib.h>
int read_line(FILE *in, char *buffer, size_t max)
{
return fgets(buffer, max, in) == buffer;
}
int main(void)
{
FILE *in;
if((in = fopen("foo.txt", "rt")) != NULL)
{
char line[256];
if(read_line(in, line, sizeof line))
printf("read '%s' OK", line);
else
printf("read error\n");
fclose(in);
}
return EXIT_SUCCESS;
}
The return value is 1 if all went well, 0 on error.
Since this uses a plain fgets(), it will retain the '\n' line feed at the end of the line (if present).
void read_file(char string[60])
{
FILE *fp;
char filename[20];
printf("File to open: \n", &filename );
gets(filename);
fp = fopen(filename, "r"); /* open file for input */
if (fp) /* If no error occurred while opening file */
{ /* input the data from the file. */
fgets(string, 60, fp); /* read the name from the file */
string[strlen(string)] = '\0';
printf("The name read from the file is %s.\n", string );
}
else /* If error occurred, display message. */
{
printf("An error occurred while opening the file.\n");
}
fclose(fp); /* close the input file */
}
This is a Simple way to get the string from file.
#include<stdio.h>
#include<stdlib.h>
#define SIZE 2048
int main(){
char read_el[SIZE];
FILE *fp=fopen("Sample.txt", "r");
if(fp == NULL){
printf("File Opening Error!!");
}
while (fgets(read_el, SIZE, fp) != NULL)
printf(" %s ", read_el);
fclose(fp);
return 0;
}

Resources