Get the user to enter a name but using file stream *fp - c

I am a beginner in c so I have a problem with get the user to input last name, a comma & then first name. However it will pass to the function call
int get_name(FILE *fp)
in my main function. I have a problem either if I have to use the arguments parameters.
Example, main (int argc, char *argv[])) or just main (void))
and from what I have been searching so far, FILE*fp cannot get the user to enter from stdin it only use to open the file(?) BUT I am required to get the user to input from keyboard and pass to the function. I have written some codes. but they don't seem to work but I am going to put down on here the one I am sure that I need a few changes most.
#define LINESIZE1024
int main(void){
FILE *fp;
char line[LINESIZE];
char first;
char last;
char comma;
while(1){
if(!fgets(line,LINESIZE,stdin)){
clearerr(stdin);
break;
}
if(fp = (sscanf(line,"%s %s %s",&last,&comma,&first)==3))
get_name(fp);
if(get_last_first(fp)== -1)
break;
printf("Please enter first name a comma and then last name");
}
BUT I got an error saying I can't use pass it from pointer to an integer. and many MORE but I accidentally closed my concolse and all the errors that appeared while I was trying to fix are gone. So please give me some ideas.
What about seconde code
while(1){
if(!fgets(line,LINESIZE,fp)){
clearerr(stdin);
break;
}
if(sscanf(line,"%s %s %s",last,comma,first)==3)
get_last_first(fp);
return 0;
}
It gave me errors too. fp,last,first,comma used uninitialized in this function
OK so I think I have fixed the previous problem now. However it doesn't print the name back if the name is given correctly. Here is my fixed main code.
int main(void){
FILE *fp = stdin;
char line[LINESIZE];
char first[16];
char last[16];
while(1){
if(!fgets(line,LINESIZE,stdin)){
clearerr(stdin);
break;
}
if(sscanf(line,"%s ,%s",last,first)==2)
if(get_name(fp)==2)
printf("Your name is: %s %s\n", first, last);
}
return 0;
}
here is my function.
int get_name(FILE *fp){
char line[LINESIZE];
char last[16], first[16];
int n;
/* returns -1 if the input is not in the correct format
or the name is not valid */
if(fgets(line, LINESIZE, fp) == NULL) {
return -1;
}
/* returns 0 on EOF */
if((n = sscanf(line, " %[a-zA-Z-] , %[a-zA-Z-]", last, first)) == EOF) {
return 0;
}
/* prints the name if it's valid */
if((n = sscanf(line, " %[a-zA-Z-] , %[a-zA-Z-]", last, first)) == 2) {
return 2;
}
return 1;
}
I thank you people so much for taking time to read and help me. Please don't be mean :)

Seems that you are making it more complicated than needed. Don't call fgets and scanf in main. Only do that in the function get_name.
It can be something like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LINESIZE 1024
int get_name(FILE *fp)
{
char line[LINESIZE];
char* t;
if(!fgets(line, LINESIZE,fp))
{
printf("Error reading input\n");
return 0;
}
t = strstr(line, ",");
if (t)
{
*t = '\0';
++t;
printf("First: %s - Last: %s\n", line, t);
return 2;
}
printf("Illegal input\n");
return 0;
}
int main(int argc, char **argv)
{
get_name(stdin);
return 0;
}
If you later decide that you want to read from a file, you can reuse the function get_name without changing it at all. All you need is to change main. Like:
int main(int argc, char **argv)
{
FILE* f = fopen("test.txt", "r");
if (f)
{
get_name(f);
fclose(f);
}
else
{
printf("Open file failed\n");
}
return 0;
}

If you want to read from the keyboard, read from stdin or use scanf, which internally reads from stdin. If you want to read from a file instead, use FILE *fp, but don't forget to open the file and check if it was successful (you'll find lots of tutorials for this).
Further, when reading in strings, you need an array of characters, not a single one. Note further, that scanf can already deal with formats like "everything that is not a ',' then a ',' then a string. Note that format "[^,]" means "any character except a ',':
So you could adapt the code as follows:
#define LINESIZE 1024
int main(void){
char line[LINESIZE];
char first[LINESIZE];
char last[LINESIZE];
while(fgets(line,LINESIZE,stdin)) {
if(sscanf(line,"%[^,],%s",last,first)==2) {
printf("Read in %s ... %s\n",last,first);
}
else {
printf("Please enter first name a comma and then last name");
}
}
return 0;
}
And if your professor is picky concerning the "use FILE*", you could write:
FILE *fp = stdin;
...
while(fgets(line,LINESIZE,fp)) {
...

Related

Beginner, trying to read file returns a null pointer in ubuntu

#define max 5
typedef struct
{
char tar[20];
int trab[31];
}data;
int main()
{
int i,j, aux;
char fname[25];
data inf[max];
/*for(i=0;i<max;i++)
{
strcpy(inf[i].tar,inf[i-1].tar);
}*/
printf("File name?");
scanf(" %s", fname);
FILE *f=fopen("fname","r");
if(f== NULL)
{
printf("Cannot find\n");
return 1;
}
I try to read a file I'm very certain is in the same dir, however each time the FILE pointer returns NULL.
I would appreciate any help :(
Although you've tagged this as C++, your code looks more like C, so I'm using a C signature for main. The main problem you have is quotes around fname. Your code is ignoring the path that was entered and trying to open a file with the literal name fname.
int main(void)
{
int i,j, aux;
char fname[25];
printf("File name? ");
scanf(" %24s", fname); /* Always use width specifier on %s */
FILE *f=fopen(fname, "r"); /* No quotes around fname */
if( f == NULL ){
perror(fname);
return 1;
}
...

Arguments of function main() in searching files

I write some code which should search string of characters in the given text files. When no argument is given you receive information it return an information that you shoul give at least one argument. If you give to program only one argument which is string of character to find you have to write how many filest do you want to search. Next step is to give path for those files. The problem is when you write more than one. The last path is only searched. The first loop indicated that paths are assigned well but printf after the loop show that sometning went wrong. What I should change at this code?
Code added below.
For any help thank's a lot.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]){
if(argc==1){
printf("No arguments given");
return -1;
}else if(argc==2){
int i=1,path_quantity=0;
while(path_quantity==0){
printf("How many path will you given:\n");
scanf("%d",&path_quantity);
}
char path[30];
int c;
for(i;i<=path_quantity;i++){
printf("Give path numver %d:\n",i);
scanf("%30s",wyraz);
fflush(stdin);
argv[1+i]=path;
printf("%s\n",argv[1+i]);
}
printf("0: %s 1: %s 2: %s 3: %s 4: %s\n",argv[0],argv[1],argv[2],argv[3],argv[4]);
int j;
for (j=2; j<path_quantity+2; j++){
FILE *f= fopen(argv[j], "r");
if(!f) {
perror("Can't open file\n");
return EXIT_FAILURE;
}
char *line = NULL;
size_t len = 0;
ssize_t nread;
while ((nread = getline(&line, &len, f)) != -1) {
char *occur = strstr(line, argv[1]);
if(occur != 0){
printf("%s", line);
}
}
fclose(f);
}
}
}
You should not change content or argv argv is a constent array of pointer.
for(i;i<=path_quantity;i++){ printf("Give path numver %d:\n",i); scanf("%30s",wyraz); fflush(stdin); argv[1+i]=path; printf("%s\n",argv[1+i]); }
Instead of using argv you should use array of pointer implementaion through malloc.please read about dynamic array of pointer implementaion that will solve your problem.

Print out first line of input file char by char, but nothing comes to screen

So Im trying to print out the first line of a file thats being passed in lets say its a plain text file with a couple of words in the first line.
I open the file and pass it through a function that does some work on the file called process. This little bit of work if for debugging reason , because my ultimate goal is to read in the entire text file line my line and process each line and reverse the words in that line.
But im stuck here i run the program with a text file argument and i get nothing in return and i know my logic sounds right i think? I just want this to ultimately printout every character in that line. Then eventually put all those characters in a char array or char instream[500]
Can someone tell me what iam doing wrong?
#include <stdio.h>
#include <stdlib.h>
void process(FILE *infile);
int main(int argc, char *argv[])
{
int i;
FILE *fp;
printf("argc = %d\n",argc);
for(i = 1 ; i <= argc; i++)
{
fp = fopen(argv[i], "r");
if(fp == NULL)
{
printf("The file: %s doesnt exist.\n", argv[i]);
}
else
{
printf("The file: %s does exist \n",argv[i]);
process(fp);
}
}
return 0;
}
void process(FILE *infile)
{
int k =0;
char iochar;
char instream[500];
while((iochar = getc(infile)) != '\n')
{
printf("Hi there %c", iochar ); // nothing prints out here why not??
//instream[k++] = iochar;
}
}

Debug Assertion Error in C

got some code here that won't compile correctly because it is saying that my pointer is already null when i am testing for a not null expression in my main function. here is the code :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXCODE 53
#define MAXMESSAGE 256
void getCode(char *codeIn, char *filename) {
FILE *codeFile;
/* Open the file with the code */
codeFile = fopen(filename, "r");
if (codeFile == NULL) {
printf("Error opening the code file - program terminated\n");
exit(1);
}
/* Read the first (and assumed only) line from the file */
fgets(codeIn, MAXCODE, codeFile);
/* Terminate the string with /0 */
codeIn[MAXCODE] = '\0';
/* Close the file */
fclose(codeFile);
return;
}
int getMessage(int *message, char *filename) {
FILE *messageFile;
int counter = 0;
/* Open the file with the message */
messageFile = fopen(filename, "r");
if (messageFile == NULL) {
printf("Error opening the message file - program terminated\n");
exit(1);
}
/* Read one number at a time from the file and store it */
while (!feof (messageFile))
{
fscanf (messageFile, "%d", (message+counter));
counter++;
}
/* Close the file */
fclose(messageFile);
return (counter);
}
void sortMessage(int *message, int size) {
int i, j, temp;
for (i=0; i<size-1; i++) {
for (j=i; j<size; j++) {
if (message[i]>message[j]) {
temp = message[i];
message[i] = message[j];
message[j] = temp;
}
}
}
return;
}
void decodeMessage(char *codeIn, int *message, int size) {
FILE *outputFile;
int i = 0;
/* Open the output file */
outputFile = fopen("csis.txt", "w");
if (outputFile == NULL) {
printf("Error opening the output file - program terminated\n");
exit(1);
}
for (i=0; i< size; i++) {
fprintf(outputFile, "%c", codeIn[message[i]%100]);
printf("%c", codeIn[message[i]%100]);
}
printf("\n");
/* Close the file */
fclose(outputFile);
return;
}
int main(int argc, char *argv[])
{
char code[MAXCODE];
int msg[MAXMESSAGE];
int msgSize;
if (argc != 3) {
printf("This program takes two arguments: the name of the file with the code, and the name of the file with the encoded message\n");
}
getCode(code, argv[1]);
msgSize = getMessage(msg, argv[2]);
sortMessage(msg, msgSize);
decodeMessage(code, msg, msgSize);
return;
}
So basically my code is using two files called codefile.txt and msgfile.txt to decode the secret message and write the decoded sequence to a new text file called csis.
As woolstar pointed out in the comments, you don't need to NUL terminate your codeIn array following fgets, because fgets will do that for you. In fact, this constitutes an overflow which we can best see by considering what happens when MAXCODE is 1: codeIn contains only one element: codeIn[0], and accessing codeIn[1] is an error.
Similarly, since MAXCODE is 53 and that's how many elements pointed to by codeIn, codeIn[message[i]%100] is suspicious because there's a potential for message[i]%100 to be an invalid index. While we're on this note, it might be wise to make message[i] an unsigned int so that it can't be negative. The format specifier (for printf and scanf) corresponding to unsigned int is %u.
while ( !feof(messageFile) ) is wrong because the EOF flag isn't set until an attempt is made at reading. Between attempting to read and your EOF test, however, you've incremented counter which means you've counted one too many items. Perhaps your loop should look like this:
while (fscanf(messageFile, "%d", (message+counter)) == 1)
{
counter++;
}
Note that this code assumes you've chosen to keep message[i] as an int. If you've chosen to use unsigned int instead, of course you'll want to use the %u format specifier.
You can probably see that feof is mostly superfluous... You can usually test for erroneous reads by checking the return value. Try to avoid feof in the future.
Your main function has a return type of int, yet at the end of it you have a return; statement which doesn't return an int value. Remove that. It's probably causing errors during compilation.
Presumably, when argv != 3 you want to return from main so you don't end up processing invalid arguments... Make sure you return an int value, e.g.
if (argc != 3) {
printf("This program takes two arguments: the name of the file with the code, and the name of the file with the encoded message\n");
return 0;
}

Trying to simulate grep command

I am getting segmentation fault when i compile my code.
I am not getting what is wrong with my code will be happy if someone can help me.
#include<stdio.h>
#include<string.h>
int main(int argc,char *argv[])
{
FILE *fp;
char fline[100];
char *newline;
int i,count=0,occ=0;
fp=fopen(argv[1],"r");
while(fgets(fline,100,fp)!=NULL)
{
count++;
if(newline=strchr(fline,'\n'))
*newline='\0';
if(strstr(fline,argv[2])!=NULL)
{
printf("%s %d %s",argv[1],count,fline);
occ++;
}
}
printf("\n Occurence= %d",occ);
return 1;
}
See man open and man fopen:
FILE *fp;
...
fp=open(argv[1],"r");
open returns an integer, not a file pointer. Just change that line to
fp=fopen(argv[1],"r");
Note: OP edited this error out of the code in the question, for those who wonder what this is about
Which leads us to (some other minor issues addressed as well - see comments):
+EDIT: point to places where error checking should be done:
#include<stdio.h>
#include<string.h>
#include <errno.h>
int main(int argc, char *argv[]) {
FILE *fp;
char fline[100];
char *newline;
int i, count = 0, occ = 0;
// for starters, ensure that enough arguments were passed:
if (argc < 3) {
printf("Not enough command line parameters given!\n");
return 3;
}
fp = fopen(argv[1], "r");
// fopen will return if something goes wrong. In that case errno will
// contain the error code describing the problem (could be used with
// strerror to produce a user friendly error message
if (fp == NULL) {
printf("File could not be opened, found or whatever, errno is %d\n",errno);
return 3;
}
while (fgets(fline, 100, fp) != NULL) {
count++;
if (newline = strchr(fline, '\n'))
*newline = '\0';
if (strstr(fline, argv[2]) != NULL) {
// you probably want each found line on a separate line,
// so I added \n
printf("%s %d %s\n", argv[1], count, fline);
occ++;
}
}
// it's good practice to end your last print in \n
// that way at least your command prompt stars in the left column
printf("\n Occurence= %d", occ);
return 1;
}
ps: so the error occurs during runtime and not during compile time - this distinction is quite crucial, because hunting down a compiler failure and solving a library usage error require rather different techniques...

Resources