Is it ok to have unused parameters in C functions? [closed] - c

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
Is it ok to leave the parameters unused?
I'm trying to run the function like this:
void encoder();
void encoder(int argc, FILE* inputFP, FILE* outputFP);
Is there a need for å secound function, one for dealing with stdio and one for dealing with files? When I try to run
void encoder(int argc, FILE* inputFP, FILE* outputFP); without any arguments I get errors:
error: too few arguments to function ‘void encoder(int, FILE*, FILE*)’
encoder();```

Is it ok to have unused parameters in C function?
Yes.
Still, why not have encoder() take two FILE* instead of the names, then do (pseudo code):
main(argc, argv)
FILE * fp_in, * fp_out
if argc == 2
fp_in = open argv[1], "r"
else
f = stdin
if argc == 3
fp_out = open argv[3], "w"
else
fp_out = stdout
encoder fp_in, fp_out

To answer the general question in the title - yes, it's okay not to use all the parameters passed to a function, although it may be confusing to future maintainers.
For this specific case, instead of passing an argument count, I'd recommend using special names for the input and output files to indicate standard streams. It's a common convention among *nix command line utilities to use "-" to specify reading from standard input:
xmllint --format some_ugly_wad_of_xml | vi -
The above command pretty prints some XML and then passes the pretty-printed version to vi to edit (something I've had to do a lot lately). So instead of passing an argc, just pass the filenames and examine them to determine what to do:
if ( !strcmp( inputFile, "-" ) )
inputStream = stdin;
else
inputStream = fopen( inputFile, "r" );
This way you're not leaving any parameters "unused".

It is better to open files and read all content and fetch to variables. So you can free (close) the file and dance. After close the file, freely make stuff.

Related

How to make use of one variable in a function in another function in C [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Header file
struct some_variable {
char *variable;
uint32_t infoe;
uint8_t *info0;
};
1.c in some directory
function1:
----------
static void filename(const char *variable,
function2:
----------
int read_variable(some_variable *var)
FILE *f = NULL;
f = fopen(filename, "rb");
.
.
.
.
}
2.c in other directory
function3:
----------
int own_function()
{
char buf[256];
uint8_t cam[3];
struct some_variable var;
var.variable = "iop";
if (strncmp(var.variable, "iop", 3) == 0) {
read_variable(&var);
f = fopen(filename,"r");
while (fgets(buf, sizeof buf, f)) {
sscanf(b, "%hhX:%hhX:%hhX:"
&cam[0], &cam[1], &cam[2]);
....
}
}
function1 and function2 are in one file in some directory, function3 is in another file which I am writing.
I called function 2 in function3.
I would like to use "filename" from function2 in function3. note: I can't change function2'
You can't.
The FILE handle, f is a local variable of read_variable. Hence, it's completely inaccessible to anything outside of read_variable.
You didn't show the complete code to read_variable, but given that it opens the file handle into a local variable, I would expect it to also be invoking fclose before it returns.
If you are not permitted to modify read_variable, have you considered just copying the entire code for read_variable into your own_function call and modifying it to meet your needs?
You can't. At least not in a way that's portable and standards compliant. By the time read_variable() returns, f is already out of scope, so it's no longer guaranteed to exist. If you're familiar with the calling stack convention of your target architecture, you may be able to access the now deinitialized memory by doing out of bounds access using pointer arithmetic, and pray that anything useful still remains there, but you really shouldn't do this. Another naughty thing you can do but really shouldn't is if read_variable() didn't close the file and thus have a file handle leak, it may be possible to get access to another file pointer for the same file figuring out the file number and using OS-specific API to access the file. Both of these are doing unsafe access, and invokes undefined behaviours, so you really shouldn't do either of them.
Instead what you can do is open a new file with the same filename, as the filename is returned in var.variable after the call to read_variable(). Either that, or you must modify read_variable() or reimplement read_variable() in a file you can modify.

How to access a .txt file from command-line input in C? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
For example, I run my program like:
program.exe < text.txt
I want the program to read from file text.txt. How do I begin doing this?
Ok, as this is a textfile, you probably want to read it line by line, so
char buf[1024];
while (fgets(buf, 1024, stdin))
{
/* do whatever you need with the line that's in buf here */
}
Note your code doesn't know about the file, it just reads from standard input. With <, you tell your environment (CMD on windows, a shell like e.g. bash on *nix) to open that file for you and provide it to your program as the standard input instead of the default, the controlling terminal, which would normally just read from the keyboard.
Hint: 1024 is kind of a random pick, most text files don't have lines exceeding 1kb. You might want to modify it to better suit your expected input.
another way to do what you are looking for is
#include <stdio.h>
int main (void) {
int c;
while ((c = fgetc(stdin)) != EOF) fputc(c, stdout);
return 0;
}
some more help here

capture the "stdin redirected file location string" in c [duplicate]

This question already has answers here:
In C how do I print filename of file that is redirected as input in shell
(9 answers)
Closed 7 years ago.
I am not still sure about the wording in the question, anyway --
I have an executable that takes some values as command line argument and also takes a file from stdin like this:
user#pc:~$./executable 0.12345 0.12345 < some/directory/somefile.txt
now is there any way I can grab the file location some/directory/somefile.txt inside the code ?
what I can do is to modify the code to take the file location as another command line argument, but in that case I need to change a lot of things.
So, it would be better if I could do something like this --
int main(int argc, char **argv)
{
char cmd_prompt[80];
char file_location[80];
grab_command_prompt(cmd_prompt);
split_and_grab_last_token(cmd_prompt, file_location);
/* this line below should print: "some/directory/somefile.txt" */
printf("%s\n", file_location);
}
is it possible ?
No. The shell interprets your commandline and, seeing a < opens the file for reading, does a fork(2) and in the child process, replaces stdin with this filehandle using dup2(2) before actually executing your program.

How to read a file into a C program on Linux? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
What is the difference between running an already compiled C program with a.out file_name_here and a.out < file_name_here?
I remember something about Linux pipelines, but I cannot remember how to make the a.out file accept a file using the < symbol.
Basically what I am asking is this: how does the C code look for a C program that:
file_name_here is a text file with "hello world" as content
terminal gets "a.out < file_name_here" in command line
terminal shows output: "hello world"
a.out file_name_here passes "file_name_here" as an argument.
a.out < file_name_here is processed by the shell and presents the contents of "file_name_here" to the program on its "stdin".
Note that when you type a.out < filename, the shell handles the I/O redirection. The program is run with its standard input coming from the named file instead of from the terminal. When you type a.out filename, the program must deal with opening the file, reading it (and preferably closing it too). Neither of these examples uses a pipe. You could write cat file1 file2 file3 | a.out which would use a pipe and supply the contents of the three files as the standard input to the program.
Many programs on Unix systems are filters. If they are given file names to process, those are read. If they are given no file names, then they read standard input instead. An example of such a program is grep; other examples include cat and sort.
The general solution, in outline, is:
extern void process_file(FILE *fp); // Where the real work is done
int main(int argc, char **argv)
{
int rc = EXIT_SUCCESS;
if (argc == 1)
process_file(stdin);
else
{
for (int i = 1; i < argc; i++)
{
FILE *fp = fopen(argv[i], "r");
if (fp == 0)
{
fprintf(stderr, "%s: failed to open file %s for reading\n",
argv[0], argv[i]);
rc = EXIT_FAILURE;
}
else
{
process_file(fp);
fclose(fp);
}
}
}
return rc;
}
This will process any command line arguments as files to be read, resorting to reading standard input if no files are specified on the command line. There are legions of extra tweaks you can make to this outline. You can easily add option processing with getopt() (or getopt_long() if you're using GNU), and you can treat a file name of - as standard input if you wish. You can exit on failure to open a file if you think that's appropriate (sometimes it is; sometimes it isn't — grep doesn't, for example). You can pass the file name to the process_file() function. You can have the process_file() function report success failure, and track whether everything worked, exiting with zero only if all the operations were successful.
Just realized the problem I had. The < symbol means that the shell replaces normal user input in C with the content of the file, so all the normal calls such as fgets and sscanf work on it.

Junk values from an input file in C [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
So I have this bit of C code below. When I place printf statements to test the text from the input file, I see that I'm getting a bunch of junk values, to be more specific they are not even alphabetic or numerical, I think they are diamonds with question marks in them. I assume this means it is not processing these values the way it should be. The input file a bit of MIPS assembly code, but in this context it is only a text file. I have commented out all other parts of my program and am left with this small piece and yet I still receive the bad values. What could I possibly be doing wrong here?
The command I use to run the program on the console is:
./assembler -symbols adder.asm
Where ./assembler is the driver (argv[0])
-symbols is a tag used (argv[1])
adder.asm is the input file (argv[2])
So once opened I should be able to grab text out of this file, and it's not a problem with the file as far as I believe, it was working earlier.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdbool.h>
FILE *fp;
FILE *fp_out;
void main(int argc, char* argv[])
{
int mode;
if (strcmp(argv[1], "-symbols") == 0)
{
fp = fopen(argv[2], "r");
mode = 1;
}
else
{
fp = fopen(argv[1], "r");
fp_out = fopen(argv[2], "w");
mode = 2;
}
}
Try to add the following line right after the open section and add #include <errno.h> to the beginning.
printf("%p, %p, %d\n", fp, ftp_out, errno);
If the fp is null then there is some problem opening the file. If you do not check the return value, you can read from a wrong buffer. Maybe there is some permission problems (or whatever). Also if errno != 0 you have a problem. Check with perror <num> the errno value in command line (or see perror(3) function).

Resources