A programming beginner here so I am working on a simple program that uses the user's input to name a text file and then the program stores the ipconfig /all information in that text file. I receive an error "unrecognized or incomplete command line." I understand it's quite easy to write the ipconfig /all to a text file using the command prompt but I was hoping to get it working using C.
Thank you!
#include<stdlib.h>
#define MAX_LEN 20
int main()
{
char myfile[MAX_LEN];
printf ("Enter text file name: ");
scanf ("%s", myfile);
system("C:\\Windows\\System32\\ipconfig /all 2>&1 \\Location\myfile.txt");
return 0;
}
a lot of errors here
not using the string you just inputted
wrong escaping of backslashes
forgetting a redirection in the command line (just before the filename). Ex: system("C:\\Windows\\System32\\ipconfig /all 2>&1 > myfile.txt")
but:
you shouldn't use system for this, popen can get a command output, no need for ugly redirections
no need to silence standard error, all the interesting output is in standard output
no need to specify the path for the command it's a system command already in the path
my proposal using popen (which is missing some error checking and whatnot, but basically works) which returns you a pipe handle. Just read it char by char until the end and write the result in an output file:
#include<stdio.h>
#define MAX_LEN 20
int main()
{
char myfile[MAX_LEN];
printf ("Enter text file name: ");
fflush(stdout);
scanf ("%19s", myfile);
FILE *f = popen("ipconfig /all","r");
FILE *fw = fopen(myfile,"w");
if (fw)
{
while(1)
{
int c = fgetc(f);
if (c == EOF) break;
fputc(c,fw);
}
fclose(fw);
pclose(f);
}
return 0;
}
Related
does anyone have an idea how to save a CMD output to a .txt with C? I would like to do a ping and tracert and then ask if the result should be saved. Should it be saved, the result should be saved in a .txt.
My code is like this:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main ()
{
char Testprint1[100],Testprint2[100];
sprintf(Testprint2, "ping 127.0.0.1");
system(Testprint2);
sprintf(Testprint2, "tracert 127.0.0.1");
system(Testprint2);
printf("\nDo you want to save the output? (y)Yes / (n)No: ");
if (Answer=='j')
{
FILE *Test;
Test = fopen("Test_Log.txt", "w");
fprintf(Test, "Ping:\n%s\n\nTracert:\n%s\n",Testprint1,Testprint2);
if(Pinglog == NULL)
{
printf("Log could not be saved.\n");
system("\n\npause\n");
}
else
{
printf("Log has been saved.");
fclose(Pinglog);
system("cls");
}
}
else if(Answer=='n')
{
system("cls");
system("\n\npause\n");
}
}
The txt includes:
Ping:
ping 127.0.0.1
Tracert:
tracert 127.0.0.1
It is plausible for me that only this comes out as a result, but I have no idea how I can change that and how I can save the CMD output e.g. in a variable and then save it in the .txt.
Your code is pretty unconventional, which should be a flag that the approach tends in a messy direction. You're using C for things that are normally scripted. I'm going to focus on the use of ping.exe.
The conventional approach in C would be to use APIs to accomplish your tasks (e.g. instead of ping.exe, call IcmpSendEcho).
Your code, on the other hand, is launching a series of external processes to do your tasks, and attempting to orchestrate them. That's something scripting languages are great at, and C is rather bad at.
While it's simple to just invoke ping.exe, the downside is you only get the control that ping.exe grants you. If you on the other hand use IcmpSendEcho, you have full control over the behavior and output.
It's possible however. ping.exe (et al) output to stdout, and scripting languages (.cmd, .sh) have natural methods of redirecting stdout. By default stdout goes to the console/shell window. You can redirect stdout by using > (e.g. ping >output.txt). You can also redirect stdout in your own application, however it's not as trivial as calling system().
At very least you will need to use CreateProcess.
There are many related questions on SO, like How do I redirect output to a file with CreateProcess?
A simple example that reads the command ping and saves it to a buffer
#include <stdio.h>
#define BUFSIZE 1000
#define CMDBUFSIZE 100
int main()
{
char buf[BUFSIZE] = {0}; // Will hold cmd output
char cmdbuf[CMDBUFSIZE]; // Used to format the cmd
char *ip = "google.com";
snprintf(cmdbuf, CMDBUFSIZE, "ping %s /n 1", ip);
FILE *p = _popen(cmdbuf, "r");
if (p == NULL) {
puts("popen failed");
return 1;
}
fread(buf, BUFSIZE - 1, 1, p);
printf("%s", buf);
_pclose(p); // Make sure to _pclose so that the cmd doesn't turn into a zombie process
}
The easiest way is, to save the output directly inside the CMD command
ping 127.0.0.1 > Test_Log.txt
This saves the output of ping 127.0.0.1 to the file named Test_Log.txt
which is exactly what you want.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i;
for(i=1; i<=255; i++)
{
printf("%d %c\n",i,i);
}
}
Hey i am working my way out from i/o redirection, and i got stuck in outputting ascii table from command prompt i done this.
C:\New folder\practice> main.exe > temp.txt
C:\New folder\practice> type temp.txt
and after hitting enter (after type temp.txt) it only outputs first 26 numbers. My question is why?
Also can someone explain me how to just copy the code into text file using redirection I know how to do using FILE I/O.
Because you're using MS-DOS... er MS WinDOS, and there ASCII number 26/^Z is the end-of-text-file mark.
The feature exists so that the environment is compatible with the CP/M operating system of the early 1970s, in case you'd need to use some files that originate from that. As you've noticed, only type works like that, but more would display more... (no pun intended).
No kidding.
It is very dangerous to write non ASCII characters in a text stream. 0x10 is \n and and can be changed into the underlying system end of line which is \r\n on Windows.
The correct way is to open a file in binary mode:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i;
FILE *fd = fopen("temp.txt", "wb");
if (NULL == fd) {
perror("Error opening file");
return 1;
}
for(i=1; i<=255; i++)
{
fprintf(fd, "%d %c\n",i,i);
}
fclose(fd);
return 0;
}
That being said, commands expecting text files may stop when they read a SUB control character (CtrlZ code 0x1A), which is you current problem...
I need to access a file provided to the program from the command line in the following fashion: ./myProgram < filename
I figured you could do this with command line arguments (argv and argc), but now realize that this is not the case. I was just wondering where this file is inputted to (name or otherwise) so I can access it.
Thanks in advance!
If you're in a unix shell (zsh, bash, etc.) and do something like ./myProgram <filename, the program dosn't receive <filename in argv array. Instead, the shell parses the part with < and redirects the program's input so that it come from the file filename.
More on i/o redirection here
So, you write exactly as if you were reading from stdin (because you are reading from stdin):
#include <stdio.h>
int main()
{
char str[200];
int i;
scanf("%s", str);
scanf("%d", &i);
printf("%s %d\n", str, i);
}
I have a simple C program called a.exe, with main loop like this:
void input_console()
{
printf(">>");
char in_string[256] = {0};
fgets(in_string, 256, stdin);
parse(in_string);
}
It works like this when I start it and enter commands from my keyboard:
>>say_hello
Hello!
>>say_goodbye
Goodbye!
>>
no command found
>>blablablabla
Command blablablabla not recognized
>>
no command found
etc.
Now I would like to read input from file instead of the keyboard so I prepared in.txt like this:
say_hello
say_goodbye
blablabla
After running a.exe < in.txt (this is Windows) I get:
>>Hello!
>>Goodbye!
>>Command blablabla not recognized
>>no command found
>>no command found
>>no command found
... (infinite loop)
I guess fgets keeps getting EOF here and my parser reaction to EOF is to print no command found message.
What I would like to do is to be able to return the input stream back to stdin once the input file I used with "<" redirection is over so I can use keyboard again. Something like:
if (in_string[0] == EOF)
stop_using_a_file_as_stdin_and_go_back_to_normal();
Is there any way to do that ?
EDIT:
Answer given by Harry Johnston in the comments works:
freopen("CON", "r", stdin);
or:
freopen("CONIN$", "r", stdin);
Instead of using input redirection, you could pass the filename as a command-line argument and open it yourself.
int main (int argc, char **argv){
FILE *input = stdin;
if (argc > 2){
input = fopen(argv[1], "r");
}
// ...
Then you can switch back easily.
input = stdin;
I am working on a school project in which we have to do some operations (select, min, max) on a table saved in .txt file.
The problem is that we can't use common functions such as fopen, fscanf, fclose.
The program will be launched from command line like this: .\project.exe select parameters <table.txt
Do you have some ideas how to get content of the .txt file to stdin without using fopen?
Thanks.
You do not need to open the file - the operating environment will do it for you.
When your program is called with <table.txt, your standard input is switched to read from that file instead of the keyboard. You can use scanf to read the data, and do not worry about opening and closing the file.
Same goes for the output of your program and the >table_out.txt redirection: rather than printing to the screen, printfs in your program would be writing to a file, which would be automatically closed upon your program's exit. Of course if you need to print something to the screen when your output is redirected, you can do so by printing to stderr (e.g. fprintf(stderr, "Invalid table format\n").
There are few ways to acomplish this.
Reading STDIN
I guess the teacher wants this method in particular. The idea is reading standard input rather than particular file.
In C++ you can simply read the stdin object. Here's an example:
#include <stdio.h>
#include <string.h>
int main(void)
{
char str[80];
int i;
printf("Enter a string: ");
fgets(str, 10, stdin);
/* remove newline, if present */
i = strlen(str)-1;
if( str[ i ] == '\n')
str[i] = '\0';
printf("This is your string: %s", str);
return 0;
}
Source: http://www.java2s.com/Code/C/Console/Usefgetstoreadstringfromstandardinput.htm
Using system utils
You can call "type" util # Windows (not sure about it) or "cat" util in Linux as a subprocess to read some partticular file. But this is rather a "hack", so I do not recommend using this one.