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"
Related
I have an assignment that is requiring that my program takes in a plain text file at execution time and manipulates it to keep track of a vending machine inventory.
The file has to contain 12 rows with the details of each item in the machine that is used to populate data structs.
Would passing the file to the program require command line arguments or is it something different?
I am using a GCC compiler.
I have tried adding the address of the file to the execution command but nothing came of that.
I've assumed you need the file path to be accepted as an input to the program.
If so then it depends on how you would like to pass this information to the program, but I'm not convinced that passing command line arguments could be considered an runtime input from user. However you could pass a path to the file as an command line argument, and access it using argc and argv arguments of the main function :
int main(int argc, char *argv[])
{
//argv[0] is always name of the program
//argv[1] is the first command line argument
//and so on up to argc-1 (argv[argc-1] is the last argument)
//so, in the simplest form do:
if (argc < 2) return -1; // check if any argument was passed, as pm100 said in comments to this answer.
FILE *f = fopen(argv[1], "rb"); // change "rb" to mode you need
if (f==NULL) return -1; // file could not be opened
// process the file as you need from here
...
}
The alternative approach, reading user input at runtime using fgets could be found here. Then pass the string you got from user as an first argument to fopen.
You can, of course, mix these two approaches (checking if any command-line args were passed, and if not ask for user input) but this probably would be an overkill for a homework.
If you just need to load file from a fixed place in your filesystem, and filename won't change then simply change argv from my example to your filename or path:
int main()
{
const char filename[] = "your_file_name_here";
FILE *f = fopen(filename, "rb"); // change "rb" to mode you need
if (f==NULL) return -1; // file could not be opened
// process the file as you need from here
...
}
This question already has answers here:
Using a variable file name in C to read from multiple files with similar names?
(2 answers)
Closed 7 years ago.
Using Visual Studio 2015 how would i open and read all the file in a directory.
The Input Parameters for the program are
Number of Sensors (N): Determines the number of input files
File Location: A local directory/folder where the files are located. Each file will be named: sensor_0.txt, sensor_1.txt, ... sensor_(n - 1).txt
I can open and read individual files in the directory by hard coding them using fopen, but since the number of input files is not constant I don't know how I would read all of the files in the directory regardless of how many input files there are.
I was thinking that i would need to create the file names since the only thing changing in the file names is the sensor number but that doesn't seem to work since fopen requires a const char * file name.
I have searched for solutions and i found a DIR variable type in dirent.h header file, but that doesn't work with the the Visual Studio Compiler and a package needs to be installed in order to use that header file.
I am in an intro to programming class so i feel like installing outside programs would be the wrong approach to solving this issue, but I could be wrong. I have also looked into functions like FindFirstFile, and FindNextFile but those also seem too advanced for me.
Any help would be really would be appreciated. Thank you in advance.
If you're writing a Windows-specific application (rather than something that needs to be portable to other operating systems) then look into the FindFirstFile, FindNextFile, and FindClose APIs.
Here's a sample of how to use these APIs (based somewhat on the samples from the above links):
#include <windows.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
WIN32_FIND_DATA FindFileData;
HANDLE hFind;
if (argc != 2) {
printf("Usage: %s [target_file]\n", argv[0]);
return 1;
}
printf("Target file is %s\n", argv[1]);
hFind = FindFirstFile(argv[1], &FindFileData);
if (hFind == INVALID_HANDLE_VALUE) {
printf("FindFirstFile failed, error %d\n", GetLastError());
return 1;
}
do {
printf("File name = %s\n", FileFindData.cFileName);
} while (FindNextFile(hFind, &FindFileData));
FindClose(hFind);
return 0;
}
Disclaimer: I haven't had a Windows dev environment years, so I have no way to compile & verify this sample. It should get you pointed in the right direction, though.
You can just do it by hardcoding the base name and iterating with an index to generate the specific name, something like this
for (size_t i = 0 ; ; ++i)
{
char filepath[MAX_PATH];
FILE *file;
// In principle, you should check the return value to ensure
// it didn't truncate the name
snprintf(filepath, sizeof(filepath), "sensor_%d.txt", i);
// Try to open the file, if it fails it's probably because
// the file did not exist, but it's not the only possible
// reason.
file = fopen(filepath, "r"); // Or "rb", depends ...
if ((done = (file == NULL)) != 0)
break; // Cannot open this, probably there are no more files.
// Process the file here
}
A better way would be to pass the name to another function, so you can later change the name generation method by looking at the directory instead of assuming it.
NOTE 1: Secure c Runtime, in MSVC compiler will probably complain about fopen() and snprintf() since snprintf() uses the POSIX name style or something like that (perhaps using the safe version snprintf_s()) I don't remember. But this is standard c (as per C11) so it should compile with any c compiler.
NOTE 2: You should also, use the full path unless the files are in the CWD. Something like (assuming the files are in drive "C:")
snprintf(filepath, sizeof(filepath), "C:\\full\\path\\sensor_%d.txt", i);
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.
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.
I'm trying to open a simple .rtf file called test in C. I'm using Xcode. My code is:
#include <stdio.h>
#include <stdlib.h>
int main (int argc, const char * argv[]) {
FILE *filePtr;
filePtr = fopen("test.rtf", "r");
if (filePtr == NULL) {
fprintf(stderr, "Can't open \"test\"\n");
exit(EXIT_FAILURE);
}
else {
printf("File open successful\n");
int x;
/* read one character at a time until EOF is reached */
while ((x = fgetc(filePtr)) != EOF) {
printf("%c", x);
}
}
fclose(filePtr);
return 0;
}
I have the test.rtf file in the same directory as my Xcode.proj directory. My output is "File open successful", however I do not get anything read from the file. Am I doing this right? Thanks.
There's nothing wrong with that code at all. I tested it (albeit not in Xcode) with a file and the transcript was:
pax> echo hello >test.rtf
pax> ./qq.exe
File open successful
hello
So the obvious think to ask is what happens when you examine test.rtf? Does it actually have any content? Because, when I do:
pax> rm test.rtf ; touch test.rtf
pax> ./qq.exe
File open successful
I get the same behaviour you observe.
Also try renaming it to test2.rtf temporarily and make sure you get the error. It's possible it may be opening a different copy of the file than what you think (this often happens in Visual C since the directory the program runs in is not always what developers think at first).
It looks right.
As for the lack of output, two possibilities:
Are you sure the file has some content? Maybe ls -l test.rtf or dir test.rft
Possibly it has some control characters which cause the terminal to which it is written to suppress output.
Try moving test.rtf to your build directory. If your project is named MyProject, move it to MyProject/build/Debug/.
I can think of two things that could cause this problem. Either there is an error when calling fgetc, or you are getting output that you don't recognize.
fgetc() will return EOF when the end of the file is reached, or an error occurs. To determine if it's an error, just after your while loop try:
if (ferror(filePtr) != 0) printf("error: %d.\n", errno);
A .rtf file is not a plain text file. It likely contains a bunch of formatting information. You are expecting to see "Hello . . . ". but what you may actually see is something like:
{\rtf1\ansi\ansicpg1252\cocoartf1038\cocoasubrtf250
{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
{\colortbl;\red255\green255\blue255;}
\margl1440\margr1440\vieww9000\viewh8400\viewkind0
\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040
\f0\fs24 \cf0 Hello . . .
And you are just assuming that is GDB output, not your program's output.
Based upon your recent comments, I think you have an empty file test.rtf in the directory your program is run in, and your real test.rtf file is in some other directory. Maybe your fopen() call at some point was fopen("test.rtf", "w"); instead of fopen("test.rtf", "r");, and you later modified it.
To see the directory your program is running in, add the following to your program after the FILE *filePtr; line:
char pwd[512];
if (getcwd(pwd, sizeof pwd) != -1)
printf("In directory %s\n", pwd);
else
fprintf(stderr, "Need bigger buffer, change '512' above\n");
Then, you can open a terminal, do cd <directory>, and test for yourself if the file you want is the file your program is opening.
You probably want this file to be plain text, not rich text. Rich text has a lot of formatting encoded into the file.