put a file in argv[] of main function - c

hi I'm trying to write a program like this in visual C++
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main(int argc, char *argv[])
{
FILE *in;
char ch;
int openbracket=0,closebracket=0;
if(argc!=2)
{
printf("the number of arguments is incorrect");
getch();
exit(1);
}
if((in=fopen(arg[1],"r"))==NULL)
{
fputs("Error",stderr); exit(1);
}
ch=getc(in);
while(!feof(in))
{
if(ch=='{')
openbracket++;
else if(ch=='}')
closebracket++;
ch=getc(in);
}
printf("Open bracket==%d,close bracket=%d",openbracket,closebracket);
getch();
}
i am trying to open a file with argv[1] in this program in visual c++
can you please show me how i can put a file in argv[1] 0f main function?
Thank you

if((in=fopen(arg[1],"r"))==NULL);
if-statements do NOT end with a semi-colon. That makes this a "do-nothing" statement
arg is never declared anywhere (you have declared argc and argv, but not arg)

Related

executable file in C

I tried to write a program in C that checks if a certain file is executable or not, if it is a shell script or a binary
<apue.h> is a header from the book Advanced Programming in the UNIX Environment
I don't think the approach is exactly right (if it's a shell script or binary). I think there is a more efficient solution. Which one do you think?
In addition, what other problems does the code have?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <apue.h>
void checkIfFileExists(const char *fileName);
int main (int argc,char *argv[])
{
char *fileName = argv[1];
if (argc < 2 )
{
err_quit("File to check not specified\n");
return 0;
}
if (argc > 2 )
{
err_quit("Too many arguments\n");
return 0;
}
checkIfFileExists(fileName);
return 0;
}
void checkIfFileExists(const char *fileName)
{
if(!access( fileName, F_OK ))
{
if(!access( fileName, X_OK ))
{
printf("The file %s is an executable\n",fileName);
//check if the file is binary or shell script
}
else
{
printf("The file %s is not an executable\n",fileName);
}
}
else
{
err_quit("The file %s was not found\n",fileName);
}
}
You can use the stat methods,
#include <sys/stat.h>
...
struct stat myf;
stat(<file>,&mf);
if( mf.st_mode & S_IXUSR )
printf("execute");
The output is a bitmap from which you can extract the file permission info
look at https://www.gnu.org/software/libc/manual/html_node/Permission-Bits.html
for the permission define available.

Unexpected output for reverse file reading in C language

Here is my code but I don't know why it prints only some part of lines.
here is my code:
#include<stdio.h>
#include<sys/types.h>
#include<fcntl.h>
int main(int argc,char *argv[])
{
FILE *fpr,*fpw;
int cnt=0;
fpw=fopen(argv[2],"w+");
char buff[1000];
while((fpr=fopen(argv[1],"r"))==NULL)
{
printf("\nCan't open file %s\n",argv[1]);
scanf("re-enter file name:%s\n",argv[1]);
}
while (!feof(fpr))
{
fgets(buff,2,fpr);
if(buff[0]=='\n')
{
putc(buff[0],fpw);
fseek(fpw,0,SEEK_SET);
}
fputs(buff,fpw);
cnt++;
}
fclose(fpr);
fclose(fpw);
}
INPUT FILE:
Hrey yhis will print twicw
lets print thrice
#why not
OUTPUT FILE
lets print thrice
#why not
So.. basically what I was trying to do is actually impossible using lseek/fseek. So I found another approach , as shown in the code below:
#include <stdio.h>
#include <string.h>
#include<stdlib.h>
int main(int argc,char *argv[])
{
FILE* fr;
FILE* fw;
int l=0;
char lines[10000][100];
if( ( (fr=fopen(argv[1],"r+"))==NULL || (fw=fopen(argv[2],"w+"))==NULL ) )
{
printf("Error reading or opening files %s,%s",argv[1],argv[2]);
}
while(fgets(lines[l++], sizeof(lines[l]), fr)!=NULL);
while(l>=0)
fputs(lines[l--],fw);
fclose(fr);
fclose(fw);
}

How to parse command-line arguments from a separate function

I am attemping to parse a command-line argument from one function process_command_line which I will then use in a main function. The second command-line argument enables the name of a file input to be submitted, which will later be used to read/write files. For the time being, I will just print out the argument within the main function to ensure that it is functioning correctly. I have had no issues parsing integers using this separate function method, but cannot get a correct output when trying to parse an input file name.
EDIT: I think my issue lies in the second function where I have a line saying argv[1] = input_file;
My attempt:
#include <stdio.h>
#include <stdlib.h>
int process_command_line(int argc, char *argv[]); //declaration for command-line function
char str2[100];
int main(int argc, char *argv[]) {
printf("%s", str2);
getchar();
return 0;
}
//This function reads in the arguments
int process_command_line(int argc, char *argv[]) {
if (argc < 2) {
fprintf(stderr, "Error: Missing program arguments.\n");
exit(1);
}
//first argument is always the executable name (argv[0])
//second argument reads in the input file name
strcpy(str2, argv[1]); //I think this is where the problem lies
}
With the help of users on this question, here is my updated and functioning solution. The problem was that I wasn't calling the second function within my main function.
My solution:
#include <stdio.h>
#include <stdlib.h>
int process_command_line(int argc, char *argv[]); //declaration for command-line function
char str2[100];
int main(int argc, char *argv[]) {
process_command_line(argc, argv); //This was missing in my first attempt
printf("%s", str2);
getchar();
return 0;
}
//This function reads in the arguments
int process_command_line(int argc, char *argv[]) {
if (argc < 2) {
fprintf(stderr, "Error: Missing program arguments.\n");
exit(1);
}
//first argument is always the executable name (argv[0])
//second argument reads in the input file name
strcpy(str2, argv[1]);
}

Lex program doesn't do anything

I am trying to write a program using Lex which recognizes some letters, numbers and do minor things. The problem is that the program does not recognizes anything. In fact, I changed the rules to a simple rule to recognizes everything, but still does nothing. What's happening? Maybe it's simple (it must be, there are few lines), but I am new with Lex and I am not able to fix it. Thanks
simple.l:
%{
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
int count = 0;
%}
/*Reglas*/
%%
[a-zA-Z_]*[a-zA-Z_0-9]* { count++; printf("%s ", yytext); }
.* { count++; printf("%s ", yytext); }
%%
/*Procedimientos de usuario*/
int main(int argc, char * argv[]) {
FILE * yyin;
if(argc == 2) {
yyin =fopen(argv[1],"rt");
if(yyin == NULL) {
printf("File %s can not be opened\n", argv[1]);
exit(-1);
}
} else {
printf("Error in arguments");
exit(-1);
}
yylex();
printf("Counter : %d \n", count);
fclose(yyin);
return 0;
}
Imput file: example.txt
CSC104H1
CSC108H1
CSC204H1
CSC258H1
Also, I need to use ctrl+d to finish the program(as I saw in stackoverflow), if not, the program does not finish by itself.
int main(int argc, char * argv[]) {
FILE * yyin;
// ...
yyin = ....
}
Here, yyin is a local variable. The scanner is using the global variable with the same name, which this declaration is shadowing.
Delete the declaration and it will work fine.
Your first clue is that the scanner is evidently reading from standard input, not from the file you specified, which is why it waits for you to type an end-of-file indicator.

Save data into a file: where the adress of the file is given by the user

I ran a simulation for some data y1, y2,..yn and generate vectors w, mu. At each simulation these results are stored into a file, let us say (normally w and mu are very long vectors 10,000 entries)
/home/carlos/Documents/Results/w.txt
/home/carlos/Documents/Results/mu.txt
But if I want to run my algorithm with other data set, and do not want to lose the previous results, I have to go directly into my C code and change (or move the w.txt, mu.txt to other file)
/home/carlos/Documents/Results/OtherData/w.txt
/home/carlos/Documents/Results/OtherData/mu.txt
I do not want to go every time into my C code to change the address(or move again and again w.txt, mu.txt), I would like to just create a new folder with a name: OtherData and store the data there just giving the address
/home/carlos/Documents/Results/OtherData/
as an input for the code
I did a very simplified example but it does not work, could somebody give me a hand?
#include <stdio.h>
#include <string.h>
void main(char *dir){
char dir_happy[100] = *dir, dir_sad[100]=*dir;
FILE *ffile_happy, *ffile_sad;
strcat(dir_happy, "/happy.txt");
strcat(dir_sad, "/sad.txt");
ffile_happy = fopen("dir_happy.txt", "w");
ffile_sad = fopen("dir_sad.txt", "w");
fprintf(ffile_happy, "Hello!, happy world\n");
fprintf(ffile_sad, "Hello!, sad world\n");
fclose(ffile_happy);
fclose(ffile_sad);
}
You have the arguments to main() wrong. The proper prototype is:
int main(int argc, char *argv[]);
Where argc is the number of arguments given, and argv is a vector holding each argument. The first argument (in argv[0]) is generally the program's name.
Untested. Have fun.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_FILENAME_LENGTH 100
#define DEFAULT_DIR "."
#define HAPPY_NAME "/happy.txt"
#define SAD_NAME "/sad.txt"
int main(int argc, char **argv) {
char name1[MAX_FILENAME_LENGTH+1], name2[MAX_FILENAME_LENGTH+1];
size_t dirlen;
char *dir = DEFAULT_DIR;
FILE *ffile_happy, *ffile_sad;
if (argc == 2) {
dir = argv[1];
}
dirlen = strlen(dir);
if (len + strlen(HAPPY_NAME) > MAX_FILENAME_LENGTH) {
fprintf(stderr, "Directory name too long. Program aborted.\n");
exit(EXIT_FAILURE);
}
if (len + strlen(SAD_NAME) > MAX_FILENAME_LENGTH) {
fprintf(stderr, "Directory name too long. Program aborted.\n");
exit(EXIT_FAILURE);
}
strcpy(name1, dir); strcat(name1, HAPPY_NAME);
strcpy(name2, dir); strcat(name2, SAD_NAME);
ffile_happy = fopen(name1, "w");
if (ffile_happy == NULL) {
fprintf(stderr, "Unable to open file \"%s\" for writing. Program aborted.\n", name1);
exit(EXIT_FAILURE);
}
ffile_sad = fopen(name2, "w");
if (ffile_sad == NULL) {
fprintf(stderr, "Unable to open file \"%s\" for writing. Program aborted.\n", name2);
fclose(ffile_happy);
exit(EXIT_FAILURE);
}
/* use files */
fclose(ffile_happy);
fclose(ffile_sad);
return 0;
}
void main(char *dir) is the problem.
Main takes 2 args int/void main(int argc, char *argv[])
argc is the number of arguments to the executable.
argv[0] is the filename of the executable.
argv[1..n] are the arguments passed (normally space separated, with quotes allowed)
So /a.out Hello "Look at me" would parse as
argv[0] => './a.out'
argv[1] => 'Hello'
argv[2] => 'Look at me'

Resources