Sending a FILE pointer to a function for reading - c

I've been working on this thing for hours on end and I have searched and searched and my code still does not work right.
How do I read my FILE from a function within main using argv[] as the file that I want read?
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
FILE words(FILE *filesToRead)
{
const char *Open;
Open = (char *)filesToRead;
filesToRead = fopen(Open, "rt");
int line;
while ((line = fgetc(filesToRead)) != EOF)
{
printf("%c", line);
}
fclose(filesToRead);
}
int main(int argc, char *argv[])
{
char *ah = argv[];
words(ah);
return 0;
}

Try this:
void words(char *filename)
{
FILE *filesToRead = fopen(filename, "rt");
/* ... */
}
int main(int argc, char *argv[])
{
if (argc > 1)
words(argv[1]);
return 0;
}
To be honest (and please don't be offended) the way your code looks it seems you have skipped a few chapters in the C book you are using.

argv[] is an array of char *s. For example, if you call your program from the command line as:
my_prog.exe foo bar
Then:
argc will be 3;
argv[0] will point to "my_prog.exe"
argv[1] will point to "foo"
argv[2] will point to "bar"
So inside your main() function, if you are expecting one argument you will need to check the value of argc is 2 and then read your argument out of argv[1].

Related

Trouble with unitialized pointer

I'm having a little trouble with pointers. I know that it's probably some silly mistake by me, but I could use some help right now.
I'm making a program which has some command line arguments and I decided to
make a function called get_param(...) so that i don't have a ton of lines in my main for this purpose.
Here is the prototype for this function
bool get_param(int argc, char **argv, char *fname);
In this example I just work with one argument. My program is supposed to be called like this ./voter -i voters.txt, where voters.txt is just a file I will be using later.
In my main function I create a variable char *fnamefor the file of the name, and then I call get_param(argc, argv, fname).
The output I get is
-i = randomfile.txt
-i = (null)
Why is that? I dynamically allocate space for fname in get_param, so isn't that space supposed to 'stay' even after my function gets to its end?
Below is my code.
Thank you.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
bool get_param(int argc, char **argv, char *fname);
int main(int argc, char **argv)
{
char *fname;
if (get_param(argc, argv, fname) == false)
return -1;
printf("-i = %s\n", fname);
return 0;
}
bool get_param(int argc, char **argv, char *fname){
if (argc != 3){
printf("%s: wrong number of inline parameters\n", *argv);
return false;
}
char i[] = "-i";
if (strcmp(argv[1], i) == 0){
fname = (char *)malloc((strlen(argv[2]) + 1)*sizeof(char));
assert(fname != NULL);
strcpy(fname, argv[2]);
printf("-i = %s\n", fname);
return true;
}
else {
printf("%s: %s: no such parameter\n", *argv, argv[1]);
return false;
}
}
The copy of fname in get_param is strictly local to get_param. It's initialized to the value passed in from main (i.e., undefined), but that's all. If you want to update the value of fname in main, then you need to pass the address, then update it in get_param.
Just change the code to
bool get_param(int argc, char argv, **char **fname);
change the call to get_param(argc, argv, fname)
to get_param(argc, argv, &fname)
and inside get_param use *fname everywhere you use fname inside function.

Reading input file in C

I need to read from an input file by using C programming language to do one of my assignments.
Here's my code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char *input = readFromFile(argv);
return 0;
}
char *readFromFile(char *argv[])
{
FILE *fp;
fp = fopen(argv[1],"r");
char *input, c;
int i = 0;
while(!feof(fp))
{
c = fgetc(fp);
input[i++] = c;
}
fclose(fp);
return input;
}
I want to do this reading operation in another function, not in function main(). I tried, but couldn't do it.
When I try to do it with the code above, I get an error message that says:
conflicting types for readFromFile()
How can I fix this error and do what I want?
You have to declare readFromFile before using it. The best way to do this is to add a prototype:
char *readFromFile(char *argv[]); /* note that the identifier is useless here */
NB: By the way, there is a lot of other errors in your source code. The main one is that you don't allocate memory for input. Therefore, you will try to dereference an unitialized pointer: this leads to an undefined behavior. Since you are returning your pointer, you need to use dynamic allocation.
#include <stdlib.h>
char *input = malloc(SIZE);
Moreover, your utilisation of feof is wrong.
First of all you can choose between these:
1. Declare the function prototype;
2. Declare the function before the main.
This way the function is recognized in main.To be fast I always declare function before the main.In readFromFile you aren't allocating the memory that you need, fixed it for you:
#include <stdio.h>
#include <stdlib.h>
char *readFromFile(char *argv[])
{
FILE *fp;
fp = fopen(argv[1],"r");
char *input, c;
int i = 0;
size_t size=100*sizeof(char);
input=(char*)malloc(size);
while( (c = fgetc(fp)) != EOF )
{
if(++i == size)
{
size+= 100*sizeof(char);
input=(char*)realloc(input,size);
}
input[i-1] = c;
}
fclose(fp);
return input;
}
int main(int argc, char *argv[])
{
char *input = readFromFile(argv);
return 0;
}

concatenate each value of argv with a string

I'm working on a C program that get the command line arguments and append to them a file extension.
The execution will be something like this:
>myprogram file1 file2
and will execute another program that will use as argument file1.txt and file2.txt.
I tried doing that would add the extension and run one command (s1 is the path and s2 is argv[i] on a loop:
int getfile(char *s1, char *s2){
char *str2 = malloc(sizeof(s2)+3);
strcpy(str2,s2);
strcat(str2,".txt");
execl(s1,"program",str2,NULL);
exit(0);
}
The function will run the program for one file (>program file1.txt and >program file2.txt), but I will need to find a way to run it this way (>program file1.txt file2.txt).
I tried to modify argv directly, but I was unsuccessful.
Any advise?
Try this code:
int main(int argc, char *argv[])
{
char *buffer;
char command[512];
int i = 1;
for(i = 1; i < argc; i++){
buffer = malloc(strlen(argv[i]) + 5);
strcpy(buffer,argv[i]);
strcat(buffer,".txt");
sprintf(command,"touch %s\0",buffer);
system(command);
free(buffer);
}
return 0;
}
A simple program that has no error checking, and I like to explicitly add the string terminator.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, int *argv[]){
if(argc==1){
printf("You have not entered anything!\n");
return 0;
}
char *arr=malloc(1000*sizeof(char));
int i;
strcat(arr, argv[0]);
strcat(arr, " ");
for(i=0;i<argc-1;i++){
strcat(arr,argv[i+1]);
strcat(arr,".txt");
strcat(arr," ");
strcat(arr,"\0");
}
printf("%s\n",arr);
free(arr);
return 0;
}

Strange symbols when reading text file with fgets

When trying to read a plain text file with fgets in C, i get some strange looking output on the first line. So if the first line is meant to be "hello" it comes out as something like "ELFh` �� 20120918 (prerelease)#xxhello". Here is the code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
FILE *fr;
int i;
extern int uniq(char *previous_word, char *current_word);
char *line1 = malloc(500);
char *line2 = malloc(500);
char *temp;
for(i = 0; i<argc; i++)
{
fr = fopen (argv[i], "r");
while(fgets(line2, 499, fr) != NULL)
{
uniq(line1, line2);
temp = line1;
line1 = line2;
line2 = temp;
}
fclose(fr);
}
return 0;
}
int uniq(char *previous_word, char *current_word) {
if(!(current_word))
return 1;
if(strcmp(previous_word, current_word))
printf("%s", current_word);
return 0;
}
I've searched every description i can give of this problem on google and stack overflow and i can find nothing at all that fixes it.
Your loop must begin at index 1. argv[0] is your executable.
To check argv[0] is helpful if you have a so called multi binary executable. There you can handle different commands with just one binary. This is very helpful on embedded systems where you need to save memory.

Read From File and Store Strings into a Multidimensional Array of Strings in C

I really need to know how to fix this.
I have a file that is read and I store the strings from the file into an array that is passed as an argument, but I can't figure out how to make it work.
When I do print the content of the array it says null.
So how do I pass a multi-dimensional array of strings to readfiles() and make it save the strings in the array passed as parameter, each string in one position?
Thanks for the help.
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdio.h>
#include <strings.h>
#define max_chars_string 10000
#define n_strings 100
int main(int argc, char **argv)
{
char *filename;
char strings_hashes[n_strings][max_chars_string];
char * pointer_string = &strings_hashes[0][0];
int n_lines;
int i = 0;
filename = (char*)malloc(strlen(argv[1])*sizeof(char));
if(argc !=3){
fprintf(stderr, "Usage : %s [text_file] [cores]",argv[0]);
exit(0);
}
strcpy(filename,argv[1]);
read_lines(filename,pointer_string);
for(i = 0; i<n_lines;i++){
printf("%s \n",strings_hashes[i][max_chars_string]);
}
return 0;
}
void read_lines(char * filename, char *pointer){
FILE *fp;
char str[max_chars_string];
int i =0;
if((fp = fopen(filename, "r"))==NULL) {
printf("Cannot open file.\n");
exit(1);
}
while(!feof(fp)) {
while(fgets(str, sizeof str, fp)) {
strcpy(pointer, str);
printf("%s", str);
pointer++;
i++;
}
}
fclose(fp);
}
Change
void read_lines(char * filename, char *pointer){
to
void read_lines(char * filename, char (*pointer)[max_chars_string]){
(pointer's type needs to be "pointer to array of max_chars_string chars". When using pointers to access multidimensional arrays, the pointer type needs to know the all the dimensions except for the outermost one, so that it knows how far to skip along when incremented.)
Change
strcpy(pointer, str);
to
strcpy(*pointer, str);
Now call it as
read_lines(filename,strings_hashes);
(This is equivalent to the following, which may be clearer:)
read_lines(filename,&string_hashes[0]);
Finally, you want to print a string not an individual character, so use
printf("%s \n",strings_hashes[i]);

Resources