C Xcode question - c

I am trying to pass arguments to the command line in xCode. I have looked up this issue and have found that I need to set the working directory to the path that the file is in. Also I have to add the arguments to the arguments tab under project- edit activeexecutable. I have also done this.
I added michael.txt twice.
/* This file is saved as readtext.c, compiled as readtext */
#include <stdio.h>
void main(int argc, char *argv[])
{
FILE *fin;
char buffer[100];
printf("Michael Mazur\n");
if (argc != 2) {printf("Usage: %s filename\n", argv[0]); exit(1);}
fin = fopen(argv[1], "r");
if (!fin) {printf("Unable to open %s\n", argv[1]); exit(1);}
while (fgets(buffer, 99, fin)) fputs(buffer, stdout);
fclose (fin);
}
I keep reaching the case that there are not 2 arguments being passed. I also ran a little test program and it keeps returning that I only have 1 argument being passed no matter how many I add. Any help?

argv[0] (path to the executable) counts in argc, so if you add michael.txt twice, argc will be 3. A slightly longer description is here. (In general, when something is misbehaving like this, either use a debugger to check the values of all the variables or print them out.)
Make sure both arguments are checked and on separate lines, like this:
Also, in future please mention what version of Xcode you're using; I think from your description it's 3.x, so that's how I answered the question. The user interface varies pretty substantially between versions.

Related

Using stdin in C exclusively through a piped in file

I wrote a file parser for a project that parses a file provided on the command line.
However, I would like to allow the user to enter their input via stdin as well, but exclusively through redirection via the command line.
Using a Linux based command prompt, the following commands should yield the same results:
./check infile.txt (Entering filename via command line)
./check < infile.txt
cat infile.txt | ./check
The executable should accept a filename as the first and only command-line argument. If no filename is specified, it should read from standard input.
Edit: I realized how simple it really was, and posted an answer. I will leave this up for anyone else who might need it at some point.
This is dangerously close to "Please write my program for me". Or perhaps it even crossed that line. Still, it's a pretty simple program.
We assume that you have a parser which takes a single FILE* argument and parses that file. (If you wrote a parsing function which takes a const char* filename, then this is by way of explaining why that's a bad idea. Functions should only do one thing, and "open a file and then parse it" is two things. As soon as you write a function which does two unrelated things, you will immediately hit a situation where you really only wanted to do one of them (like just parse a stream without opening the file.)
So that leaves us with:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "myparser.h"
/* Assume that myparser.h includes
* int parseFile(FILE* input);
* which returns non-zero on failure.
*/
int main(int argc, char* argv[]) {
FILE* input = stdin; /* If nothing changes, this is what we parse */
if (argc > 1) {
if (argc > 2) {
/* Too many arguments */
fprintf(stderr, "Usage: %s [FILE]\n", argv[0]);
exit(1);
}
/* The convention is that using `-` as a filename is the same as
* specifying stdin. Just in case it matters, follow the convention.
*/
if (strcmp(argv[1], "-") != 0) {
/* It's not -. Try to open the named file. */
input = fopen(argv[1], "r");
if (input == NULL) {
fprintf(stderr, "Could not open '%s': %s\n", argv[1], strerror(errno));
exit(1);
}
}
}
return parse(input);
}
It would probably have been better to have packaged most of the above into a function which takes a filename and returns an open FILE*.
I guess my brain is fried because this was a very basic question and I realized it right after I posted it. I will leave it up for others who might need it.
ANSWER:
You can fgets from stdin, then to check for the end of the file you can still use feof for stdin by using the following:
while(!feof(stdin))

how to write a command line to a file in 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]);
}

Properly use main function arguments in C, NetBeans 7.2

I'm having a hard time trying to pass a directory path to my program on NetBeans 7.2, what I tried to do was to write "${OUTPUT_PATH}" "/home/vitor/Área de Trabalho/Programação/Teste" on the project's parameters. /home/vitor/Área de Trabalho/Programação/Teste is my directory's path, I have 3 .txt files inside it, and my program is supposed to read each one of them by adding their names in the path's ending, something like:
/home/vitor/Área de Trabalho/Programação/Teste/times.txt
Here is my piece of code:
int main(int argc, char *argv[]){
if(argc == 1){
printf("ERROR: The directory's path wasn't informed.");
exit(1);
}
else{
char endtimes[200];
strcpy(endtimes, argv[1]);
strcat(endtimes, "times.txt");
}
FILE *caminho;
caminho = fopen(endtimes, "r");
if (!caminho){
printf("Error trying to open file.");
exit(1);
}
Everytime I try to run the code, it displays Error trying to open file. I checked argc and it's value is 4 (which I guess is not right.) I don't have enough experience using netbeans, in fact, this is my first program to work with files. So, could you guys help me?
I'm using Ubuntu 13.
Thanks for your patience.
--EDIT--
I made changes on the project's parameters according to the comments below, endtimes is storing the correct file path : /home/vitor/Área de Trabalho/Programação/Teste/times.txt but I still get Error trying to open file. Should the file path be different because I'm using Ubuntu 13?
argv[0] is the executable's name and if you've passed 3 arguments in the form of filenames, those will be stored in argv[1], argv[2] and argv[3], respectively. So you might want something like:
strcpy(endjogos, argv[1]);
strcat(endjogos, "jogos.txt");
strcpy(endtimes, argv[2]);
strcat(endtimes, "times.txt");
strcpy(endapost, argv[3]);
strcat(endapost, "apostas.txt");
Note that C arrays are zero-indexed, so with argc==4, you have argv[0], argv[1], argv[2], argv[3].
If you have a program call like this "main.out -one.txt -two.txt tree.txt" you have 4 parameters. Thereforeargc will be 4
argv[0] will be "main.out"
argv[1] will be "one.txt"
argv[2] will be "two.txt"
argv[3] will be "tree.txt"

Confused about command prompt, Visual Studio exe's and text files?

The title doesn't really do this topic justice. It's actually quite simple, my problem that is. I have a program (code below) written in the C language. I want this program to create an exe file that can be ran through the command prompt console window and that will also take a text file as a parameter. So, long story short; I need it to say this on the command line in CMD:
C:\Users\Username\Desktop\wrapfile.exe content.txt
My only problem is getting the code right. I want to tell Visual Studio: "The file you should open is given in the command prompt window as a parameter, there is no set location..."
How do I do that?
Here is my working code (Although you will have to change a few things in the *fp definition.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE *fp; // declaring variable
fp = fopen("c:\\users\\*Put you're PC username here*\\Desktop\\contents.txt", "rb"); // opens the file
if (fp != NULL) // checks the return value from fopen
{
int i;
do
{
i = fgetc(fp); // scans the file
printf("%c",i);
printf(" ");
}
while(i!=-1);
fclose(fp);
}
else
{
printf("Error.\n");
}
}
Thanks everyone!
As Ken said above, the arguments of the main method are the values that you pass in from the command line. Argc is 'argument count' and argv is 'argument values'. So to open the fist argument passed in from the command line, change
fp = fopen("c:\\users\\*Put you're PC username here*\\Desktop\\contents.txt", "rb"); // opens the file
to
fp = fopen(argv[1],"rb");
Just make sure to do error checking (ie argv[1] is not null) before you try to fopen the input. Also FYI, in your case argv[0] will be the name of your executable.

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