Linux terminal file opening - c

This is some code that I wrote but I am confused to how to run it with linux terminal.
I tried writing like this:
asdasd:~/folder/file>./main.c file.txt but I just keep getting permission denied.
Do I need some other program to run this with? I hope I gave enough information to get some kind of feedback
(file.txt is the file I am trying to start the program with)
...........
void fileReader(int number, char *vector[])
{
if(number!= 2)
{
printf("File: %s filename\n", vector[0]);
exit(1);
}
FILE *file = fopen(vector[1], "r");
if(file == 0)
{
printf("File cannot be opened\n");
exit(1);
}
..........
........

You have to compile the program.
You do that with
gcc main.c -o program
Then you start it with:
./program file.txt

depending on which Linux OS you're running with (MAC already has this pre installed), just go to the terminal, and change the path to the folder where your program is. then do gcc main.c -(any file name that you want, you can even just name this 'main'). then you can just type main, and it'll run your program for you.

Related

C fopen() unable to open file in /tmp

I am following the basic C programming tutorial on tutorialspoint.com
I have the following program which generates a file in /tmp called test.txt:
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen("/tmp/test.text", "w+");
fprintf(fp, "This is testing for fprintf...\n");
fputs("This is testing for fputs...\n", fp);
fclose(fp);
return 0;
}
Then I have a second program which just tries to open that file for reading:
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main() {
FILE *fp = NULL;
fp = fopen("/tmp/test.txt", "r");
if (fp == NULL) {
printf("NULL!!!\n");
}
printf("%s\n", strerror(errno));
fclose(fp);
return 0;
}
However, when I try to run the program that opens the file, I get the following output:
NULL!!!
No such file or directory
Segmentation fault
If I modify the code to point to the same file in my home directory, it works correctly. It seems that, for some reason, I am not able to open files in the /tmp directory (via fopen)... And just to be clear, I am able to change to /tmp and cat the contents of the test.txt file just fine. Permissions look normal on it as well, 664 with my user as the owner and group.
The only other specifics that I can think of that might have to do with my system is that I am on Elementary OS Juno, I am using g++ 7.3.0 (clang also gives the same result), and I have separate encrypted partitions for my OS root and home...
Any thoughts on what might be causing this?
This was simply caused by an incorrect file extension, .txt vs.text as pointed out by #yano

GCC/Command Prompt error: '.' is not recognized as an internal or external command

I'm fairly new to C and am completely new to using the command prompt and GCC to compile and run my programs. I'm struggling to find the right words to ask this question properly so please bear with me, I am doing my best.
I need to use GCC to compile and run this C program but I'm getting an error that I do not understand. In this example program, I was told to use these lines to compile and run the code:
$ gcc -Wall -std=c99 -o anagrams anagrams.c
$ ./anagrams dictionary1.txt output1.txt
So that is what I did. GCC does compile the program file, so the first line does not give me any error. But GCC does not like the second line, as shown below:
C:\Users\...\Example>gcc -Wall -std=c99 -o anagrams anagrams.c
C:\Users\...\Example>./anagrams dictionary1.txt output1.txt
'.' is not recognized as an internal or external command,
operable program or batch file.
Everywhere I look, it says to use "./filename" to run the program after compiling so I don't understand why it is not working for me. Any help or advice would be really appreciated.
Also, here is the main() of the program to show why those two .txt files are needed:
int main(int argc, char *argv[])
{
AryElement *ary;
int aryLen;
if (argc != 3) {
printf("Wrong number of arguments to program.\n");
printf("Usage: ./anagrams infile outfile\n");
exit(EXIT_FAILURE);
}
char *inFile = argv[1];
char *outFile = argv[2];
ary = buildAnagramArray(inFile,&aryLen);
printAnagramArray(outFile,ary,aryLen);
freeAnagramArray(ary,aryLen);
return EXIT_SUCCESS;
}
'.' is not recognized as an internal or external command
This is not a GCC error. The error is issued by the shell when trying to run a command.
On Windows this
./anagrams dictionary1.txt output1.txt
should be
.\anagrams dictionary1.txt output1.txt
as on Windows the path delimiter is \ as opposedto IX'ish systems where it is /.
On both systems . denotes the current directory.
The reason for the crash you mention in your comment is not obvious from the minimal sources you show. Also this is a different question.

About `argv` and opening a file with command line

I have this code:
#include <stdio.h>
int main ( int argc, char *argv[] )
{
FILE *file;
int x;
if ( argc != 2 )
printf( "Use: %s file name", argv[0] );
else {
if ((file=fopen( argv[1], "r" ))== 0 )
printf( “Couldn't open the file.\n" );
else {
while (( x = fgetc( file ) ) != EOF) printf( "%c", x );
fclose( file );
}
}
return 0;
}
Now, having this code, how do I execute a file from terminal (that is on the pic as well as my configuration of NetBeans). http://i.stack.imgur.com/6WRh3.png
First, better replace your statement (in your program above)
printf( “Couldn't open the file.\n" );
with
perror(argv[1]);
then, simply compile your program in your terminal, e.g. type there a shell command similar to
gcc -Wall -g mysource.c -o myprog
(Read more about invoking GCC: the -Wall option asks for nearly all warnings and is very useful -so never miss it-; you could even add -Wextra to get even more warnings; the -g is asking for DWARF debugging information in the ELF executable and enables you to use later gdb)
assuming your source code is in a file named mysource.c in the current working directory (use pwd command to query that current directory, ls -al to list it, and cd builtin command to change it)
at last, run your program as
./myprog sometestfile.txt
You might want to use the debugger. Read first about GDB, and try perhaps
gdb ./myprog
(I am guessing you are on Linux or some other POSIX compliant operating system, and using GCC compiler)
Read more about perror(3), command line interface, shells, globbing, glob(7), PATH variable
Later, you'll want to have some bigger program of yours made in several translation units, having some common header file (to be #included in all of them). Then you'll use a builder like GNU make. You could use a good editor like emacs, some version control like git, etc...
(you might realize that NetBeans is not very useful, because you can have even better developing comfort with your own collection of tools; having the freedom to choose your tools is worthwhile!)
PS. Perhaps replace printf( "%c", x ); with the shorter and more efficient putchar(x); ...

Is there a way of opening a directory from a specific path using stdio.h and stdlib.h?

I'm trying to make a program in C which gets a path of a directory and does things with the files inside.
Is there any way of doing this without using dirent.h or dir.h?
Also, is there any function which opens a directory with a url such as fopen but that opens files with a url path?
The C language does not have the notion of directories so there is no standard C way of using them.
The <dirent.h> thing is a POSIX API, so it should be available in any *nix OS. Other oses have other mechanisms to read the directory. For example, in Windows there is FindFirstFile()/FindNextFile().
You could use a third party, OS agnostic library, of course, but it will use any of these APIs under the hood.
On modern Unix-like systems, the answer is No (even though you can open a directory for reading, you can't actually read from it).
If you go back far enough in history, the answer was 'sometimes'. If you look at p183-4 of the second edition of K&R, you will see code reading a directory directly. That simply does not work on current versions of Unix.
You might be able to open a directory for reading, but you can't then do anything more with it.
$ cat opendot.c
#include <stdio.h>
int main(void)
{
FILE *fp = fopen(".", "r");
if (fp != 0)
{
printf("OK\n");
char buffer[256];
size_t nbytes;
if ((nbytes = fread(buffer, sizeof(char), sizeof(buffer), fp)) > 0)
{
for (size_t i = 0; i < nbytes; i++)
printf("0x%.2X\n", buffer[i]);
}
else
printf("Read failed\n");
fclose(fp);
}
else
printf("Failed\n");
return 0;
}
$ make opendot
gcc -O3 -g -std=c11 -Wall -Wextra -Werror opendot.c -o opendot
$ ./opendot
OK
Read failed
$
(Tested on Mac OS X 10.10.3 with GCC 5.1.0.)
You can use open() to open a directory for reading, primarily so you can use the file descriptor in operations such as fchdir() and
openat(). The fopen() calls illustrated above use the open() function underneath.
But you can't actually read from the directory.

input redirection on CMD

Well, I am learning programming in C, and I got an assignment to get 3 characters from an input text file into 3 variables and then print their ASCII values.
I wrote this code:
#include <stdio.h>
int main()
{
char a,b,c;
printf("Insert 3 characters:\n");
a=getch();
b=getch();
c=getch();
printf("%d, %d, %d",(int)a,(int)b,(int)c);
}
I opened a text file (input.txt) and wrote there: "abc".
I managed to compile the code with the MinGW compiler, and on the CMD window that I opened in the folder of the .exe file, I wrote: "Task.exe <input.txt".
The program ran normally. I mean, it waited for me to input 3 characters.
What have I done wrong in my work?
help me please :)
You are asked to read from an input text file.
Why don't you use fopen to open a file handle, and fgetc to read from it?
You could perhaps use fscanf. Don't forget to use the resulting count.
And of course, you should call fclose. Using perror is useful to handle error cases.
So start your code with something that checks that your program has an argument, then fopen it:
int main(int argc, char**argv) {
if (argc<2) { fprintf(stderr, "missing program argument\n");
exit(EXIT_FAILURE); };
FILE* fil = fopen(argv[1], "r");
if (!fil) { perror(argv[1]); exit(EXIT_FAILURE); };
Then run Task.exe input.txt in your console (no redirection needed!).
You should take the habit of reading the documentation of every function you are using, of testing failure cases, of compiling with all warnings & debug info (gcc -Wall -Wextra -std=c99 -g), and of using the debugger (gdb).

Resources