how to write a command line to a file in c - c

I'm having issues with writing this command line to a file and it's suppose to output to the screen. To me, my code looks like it should work but I'm at a complete loss (this is my first time programming in C)
Print one line describing your program
Open the first parameter as a file for writing. If no parameter is provided, write to the stdout handle
Using a loop, save the contents of the array of string pointers passed as a parameter to the main function into the file open for writing. This is usually the variable named argv.
int main(int argc, char *argv[])
{
FILE *fp;
int i;
printf("Output supplying 'multiple arguments' to this program");
fp = fopen(argv[1], "w"); //Write to file
if(fp==NULL)
{
fp = stdout;
}
for(i=0;i<argc;i++)
{
fprintf(fp, argv[i]);
}
printf("The number of arguments printed %d", argc);
return 0;
Any help provided would be greatly appreciated!

Don't ever use dynamic format strings in C. This opens you up to an extensive set of bugs, several of them security-sensitive. Instead, pass a format string that indicates your intent, like so:
for(i=0;i<argc;i++)
{
fprintf(fp, "%s\n", argv[i]);
}

Related

Problems about yyin and yyout using in lex for lexical analysis

This is main function for lexical analysis.
If I use yyin for getting data from file, yyout execute and writes to file, but when I give codes from terminal yyout isn't working. How can I solve that?
int main(int argc, char *argv[])
{
extern FILE *yyin, *yyout;
char *input;
printf("flexing there\n argc=%d\n argv[0]=%s argv[1]=%s \n",argc,argv[0],argv[1]);
if(argc > 1 && strstr(argv[1],".g++") != NULL){
printf("we will read your file = %s\n",argv[1]);
yyin = fopen(argv[1], "r");
}
else if(argc > 1){
printf("your file type is wrong ,must be .g++ type\n");
return 0;
}
else{
printf("enter your code please\n ");
}
yyout = fopen("outputlex.txt", "w");
yylex();
return 0;
}
I use yyout at rule section like that
%%
"(" fprintf(yyout,"OP_OP\n");
%%
In C, when you write to a file, the output is kept in a buffer until there is enough data to make it worthwhile writing, typically around 4kb. So if you just write a few bytes, you won't see anything in the file until it is closed.
By contrast, when you write to the terminal, the output is usually only buffered until a newline character is written. And if you write to stderr, the output is always immediate.
You can change the buffering for a stream by calling setvbuf right after the fopen. You can also force the stream's buffer to be sent using fflush.

Read input.txt file and also output.bmp file from terminal (C-programming)

I have to do an assignment where I have to write a C-Programm, where it gets the input-file-name from the console as command line parameter.
It should move the data from the input.txt file (the input file has the information for the bmp file - color etc.) to the generated output.png file. The 20 20 parameters stand for width and height for the output.png image.
So the console-request for example (tested on Linux) will look like this:
./main input.txt output.bmp 20 20
I know that this code reads an input.txt File and puts it on the screen.
FILE *input;
int ch;
input = fopen("input.txt","r");
ch = fgetc(input);
while(!feof(input)) {
putchar(ch);
ch = fgetc(input);
}
fclose(input);
And this would (for example) write it to the output.png file.
FILE *output;
int i;
output = fopen("ass2_everyinformationin.bmp", "wb+");
for( i = 0; i < 55; i++)
{
fputc(rectangle_bmp[i], output);
}
fclose(output);
But this code works only, if I hard-code the name directly in the code, not by using a command line parameters.
I don't have any clue, how to implement that and I also didn't find any helpful information in the internet, maybe someone can help me.
Greetings
The full prototype for a standard main() is
int main(int argc, char* argv[]);
You get an int with the number of arguments, argc and
a list of "strings" (as far as they exist in C), argv.
You can for example use
#include "stdio.h"
int main(int argc, char* argv[])
{
printf("Number: %d\n", argc);
printf("0: %s\n", argv[0]);
if (1<argc)
{
printf("1: %s\n", argv[1]);
}
}
to start playing with the arguments.
Note that this is intentionally not implementing anything but a basic example of using command line parameters. This matches an accpeted StackOverflow policy of providing help with assignments, without going anywhere near solving them.

fgets() not working.in C?

Edit: Deleted all but the main question.
My program here is supposed to create a file at a specified directory, and write specified text to it. A correct file's path and content should look something like this:
Path: D:\test.txt
Content: The printing succeeded.
For some reason, my code won't recognize the "path" variable. I don't know what I'm doing wrong here. The "text" variable works fine.
#include<stdio.h>
int main()
{
//Declaring variables
char path[999];
char text[999];
FILE *fp;
//prompting for path variable
printf("Specify a file path.\n");
fgets(path,999,stdin);
printf(path);
//prompting for the text variable.
printf("What do you want to write?");
fgets(text,999,stdin);
printf(text);
//opening and printing to file.
//fp = fopen("D:\\test.txt", "w");
fp = fopen(path, "w");
fprintf(fp, text);
fclose(fp);
//test print to see that the program completed correctly.
printf("\nThe printing has been done.");
return 0;
}
The thing I don't understand is that fp = fopen("D:\\test.txt", "w"); works, but fp = fopen(path, "w"); doesn't. I've tried putting in these different paths.:
D:\\test.txt
D:\test.txt
D\test.txt
D\\test.txt
It doesn't open the file when you open the variable path because fgets() reads the newline and puts it at the end of the string (if there's enough space in the buffer). In order to make it work you have to manually remove the newline from the string.
Try this before opening the file.
if(isspace(path[strlen(path)-1]))
path[strlen(path)-1]='\0';
You might also need to include <ctype.h>

reading data from a file into an array error in C

I am trying to read from a file specified in a command prompt through terminal using the line program < file.txt and then print it again to check it works. I get the error Segmentation fault: 11, I'm not sure if my file is opening correctly in my program.
This is the code so far:
#define MAX 1000
int
main(int argc, char *argv[]) {
FILE *fp;
double values[MAX];
fp = fopen(argv[1], "r");
fscanf(fp, "%lf", values);
printf("%f\n", *values);
fclose(fp);
return 0;
}
Any help or feedback would be greatly appreciated.
You should execute your program like
./program file.txt
I'm not sure if my file is opening correctly in my program
Then you should really test for it, you are getting a segfault because fopen is returning NULL.
#include <stdio.h>
#define MAX 1000
int
main(int argc, char *argv[]) {
FILE *fp;
double values[MAX];
fp = fopen(argv[1], "r");
if (!fp) {
printf("Invalid file name \n");
return -1;
}
fscanf(fp, "%lf", values);
printf("%f\n", *values);
fclose(fp);
return 0;
}
fopen is NULL because you are invoking the program in the wrong manner, < and > are a re-directions which can be useful but is not what you are trying to do in this case, correct way to invoke it is to simply pass it the arguments directly.
./program input.file
Yeah, either:
1) check the way you're invoking it, i.e,
check if the 'program' is an executable file, you can make it executable using chmod command in linux
check if the path to 'program' or 'file.txt' is correct
2) (I'm not sure of this): check if the content of 'file.txt' is of the right content. (I don't think it should affect to the extent that it causes a segmentation fault, but still, check it.)

How to run c program and give input in same line

I'm new to C and I'd like to ask about running a C program and supplying input at the same time.
What I would like to do is run a program (ex. fileOpener) and also state which file to open
./fileOpener < filename1
I've tried it already and it works fine, but what do I use to know what filename1 is? That way I can open the file with
fp = fopen(filename1, "r")
Thanks.
Edit: OK, I'll try to explain a bit more. If there wasn't a "<" then I could just use command line arguments as I have done before, but when I tried it with the <, it didn't work
Specifically: fileOpener code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
printf("%s", argv[1]);
}
when I use ./fileOpener < filename1 the output is ./fileOpener
I used gcc -o fileOpener fileOpener.c as the compiler
int main(int argc, char *argv[])
You can name them whatever you want, but these are the normal names.
argc is non-negative. It gives the number of useful elements in argv.
If argc is positive, argv[0] contains the program name. Then argv[1] through argv[argc - 1] point to character arrays that contain the program's command line arguments.
For example, if I run a program at the command line, such as
unzip filename.zip
argc will equal 2; and argv[0] will compare equal to "unzip"; and argv[1] will compare equal to "filename.zip".
Source
You can't do that, if you use redirection (i.e. "< filename") the file is opened by the system. You could discover the name, but it's non-portable, and anyway useless since the file is already open. Just use stdin instead of fp, and you need not use fopen() (nor fclose()):
int main()
{
char buffer[1024];
// fgets() reads at most 1024 characters unless it hits a newline first
// STDIN has been already opened by the system, and assigned to data flowing
// in from our file ( < inputFile ).
fgets(buffer, 1024, stdin);
printf("The first line of input was: %s", buffer);
}
A different approach is to use arguments:
int main(int argc, char **argv)
{
FILE *fp = NULL;
char buffer[1024];
if (argc != 2)
{
fprintf(stderr, "You need to specify one argument, and only one\n");
fprintf(stderr, "Example: %s filename\n", argv[0]);
// Except that argv[0], this program's name, counts.
// So 1 argument in command line means argc = 2.
return -1;
}
printf("I am %s. You wanted to open %s\n", argv[0], argv[1]);
fp = fopen(argv[1], "r");
fgets(buffer, 1024, stdin);
printf("The first line of input was: %s", buffer);
fclose(fp); fp = NULL; // paranoid check
return 0;
}
You need setup your program to take a command line argument. Here's a good tutorial that solves your exact question:
http://www.cprogramming.com/tutorial/c/lesson14.html
A program's main function in C has two arguments:
int main(int nArgs, char *pszArgs[]) {}
That first argument tells the program how many parameters were passed onto the program when you ran it. Usually, this will just be 1, because it includes the program's name.
The second argument is a table of strings, which can be accessed thus (the program below prints the parameters given to it):
int main(int nArgs, char *pszArgs[])
{
int i = 0;
while (i < nArgs)
{
printf("param %d: %s\n", i, pszArgs[i]);
i++;
}
return 0;
}

Resources