Modification of printf function in c - c

I have the following code in which I want to modify printf and write in a file. I have used macros for the same.
#include<stdio.h>
#define printf(A) {FILE *fp;\
fp=fopen("oup.txt","wb");\
fprintf(fp,A);\
fclose(fp);}
int main()
{
int i;
for(i=0;i<10;i++)
printf("Hello\n");
}
Above code gives error:
`this declaration has no storage class or type specifier`at fp=fopen(..) and printf in the code
Please suggest any solution.Also suggest any other way for doing the same.

#interjay, NPE - simple but brilliant answer. I will add an example with freopen:
#include <stdio.h>
int main ()
{
FILE *fp;
printf("This text is redirected to stdout\n");
fp = freopen("file.txt", "w+", stdout);
printf("This text is redirected to file.txt\n");
fclose(fp);
return(0);
}

For a multi-line macro, the backslash has to appear at the end of the line, but you have spaces after one of the backslashes.
There are also other, unrelated issues with the macro:
It won't support multiple arguments to printf.
It won't work correctly in some places (such as between if and else). You need something like the do/while(0) idiom to fix that.
To actually redirect standard output, it's better to use freopen instead.

Related

How to take the output of grep and write it to a new file

I want to take the output of the grep command on a file, create a new file and save that grep output to the new created file, can someone please point me to the right direction in how I would do that?
The path you choose depends a great deal on how simple you want it to be.
Perhaps the simplest method is the use of system:
#include <stdio.h>
#include <stdlib.h>
int main (void) {
system ("grep a *.c >outfile.txt");
return 0;
}
though you also could construct the command dynamically if you have different arguments to grep or a non-fixed output file.
Beyond that, you could use popen() (if available on your implementation - it's not mandated by ISO but is instead a POSIX thing) along with fgets() or fgetc() to read the output of that command and do whatever you want with it:
#include <stdio.h>
int main (void) {
int chr;
FILE *echo = popen ("echo hello there", "r");
if (echo != NULL) {
while ((chr = fgetc (echo)) != EOF)
putchar (chr);
fclose (echo);
}
return 0;
}
The next step up from there may be to not rely on an external grep at all but instead include something like PCRE (Perl-compatible regular expressions) into your own code, giving you much finer control over what happens.

Read file without fopen() (C language)

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.

Is this incorrect using of popen(), printf and stdout or bug in glibc?

I noticed that my program using function popen
and reassigning stdout fails with printf function
The code:
# include <stdio.h>
int main(int argc, char * argv[])
{
FILE * tmp = stdout;
char * command = "cat > newfile.txt";
double a=12.2344;
stdout = popen( command, "w"); /* permitted according to glibc tutorial */
printf("That was laddy\n"); /* This doesn't go to newfile.txt !!!*/
fprintf(stdout, "And his lass\n"); /* but This goes */
/* but this...... */
printf("A double number: %.2f\n", a); /* unexpectedly goes where the
first printf hasn't gone */
/* is it a bug or there is something wrong in a code ? */
pclose(stdout);
stdout = tmp;
return 0;
}
What's with function printf? One time it prints on tty but next time
to file 'newfile.txt' (where it should).
Is it bug with glibc or mistake in code above.
I use that redirection in my utility program.
Thanks for any suggestions.
This is clearly a bug in glibc. I can reproduce the behavior you describe with libc 2.13 on an x86 Ubuntu with Linux kernel 3.0.0-32-generic.
If I replace the first call to printf() with the equivalent fprintf(stdout,"That was laddy\n");, all the output goes to the newfile.txt file.
Since printf() is defined in terms of fprintf(stdout,...) there should never be any behavior change when converting a printf(...) call to an fprintf(stdout,...) call.
Comment out the fprintf() and see whether your 1st and 2nd printf() behaves the same way. My guess is that fprintf() is doing something unexpected in the library data structures.
try with a fflush(stdout) before popen

Redericting stdout and stdin

I would like to redericting stdout, stderr to file and stdin from char*. My goal is make it in C.
When i run this code:
int main(){
stdout=fopen("/home/user/file.txt","w");
printf("aaaa");
printf("\nbbbb");
system("/bin/bash");
sprintf("stdin","exit");
return 0;
}
File didn't have for some string and bash take argument from console. Where is bug??
You don't want to assign to stdout. Instead, you (probably) want to use freopen, in your case like: freopen("/home/user/file.txt","w", stdout);
If/when you're doing all the processing internally, you're generally better off writing the code to receive a FILE * as a parameter, and passing the correct value. That doesn't work when you have external code that writes directly to stdout though.
Edit: I should probably also mention one other serious problem with freopen -- no method is provided to restore it to the previous stream. It's up t you to use freopen again, and know the path that will write to the console (or whatever).
stdout should not be used as an lvalue. Try the fprintf() function instead of printf() to get the desired effect.
As for redirecting the stdout from bash, can you not just call it with /usr/bin/bash >> /home/user/file.txt?
#include <stdio.h>
#include <stdlib.h>
#include <io.h>
int main(void){
int ret;
FILE *fp;
int stdout_bk;
stdout_bk = dup(fileno(stdout));
fp=fopen("/home/user/file.txt","w");
dup2(fileno(fp), fileno(stdout));
ret = system("/bin/bash");
//flushall();//for vc
fflush(stdout);//for gcc
fclose(fp);
dup2(stdout_bk, fileno(stdout));//restore
return 0;
}

How to open .ttcn file using C file open functions?

I am working on TTCN-3 (Testing and Test Control Notation) scripting language. I wanted to prepare on guideline checker for this code files.
For that I want to read lines of TTCN-3 script file( some thing like file.ttcn ) one by one into a buffer. But for me fopen / sopen / open / fgetc / fscanf are not able to work properly and are not reading the file correctly. It is giving NULL. Is there any way I can read characters of it into a buffer. I think C cannot read files with more than three extension characters (like .ttcn). Forgive me if my assumption is wrong.
My Environment is Turbo C on windows.
Edit:
Yes I checked those errors also but they are giving unknown error for read()
and no such file or directory exists.
My code is as follows
#include <errno.h>
#include <io.h>
#include <fcntl.h>
#include <sys\stat.h>
#include <process.h>
#include <share.h>
#include <stdio.h>
int main(void)
{
int handle;
int status;
int i=0;
char ch;
FILE *fp;
char *buffer;
char *buf;
clrscr();
handle = sopen("c:\\tc\\bin\\hi.ttcn", O_BINARY, SH_DENYNONE, S_IREAD);
/here even I used O_TEXT and others/
if (!handle)
{
printf("sopen failed\n");
// exit(1);
}
printf("\nObtained string %s #",buf);
close(handle);
fp=fopen("c:\\tc\\bin\\hi.ttcn","r"); \\sorry for the old version of one slash
if(fp==NULL) \\I was doing it with argv[1] for opening
{ \\user given file name
printf("\nCannot open file");
}
ch=fgetc(fp);
i=0;
while(i<10)
{
printf("\ncharacter is %c %d",ch,ch);
i++; //Here I wanted to take characters into
ch=fgetc(fp); //buffer
}
getch();
return 0;
}
The most likely culprit is your Turbo C, an ancient compiler. It's techincally a DOS compiler, not Windows. That would limit it's RunTme Library to 8.3 filenames. Upgrade to something newer - Turbo C++ seems like a logical successor, but Microsoft's VC++ Express would work as well.
Your assumption is wrong about extensions. If fopen is returning NULL, you should output the result of strerror(errno) or use the perror() function to see why it failed.
Edit: The problem is probably because you have "c:\tc\bin\hi.ttcn". in C, "\t" is interpreted as tab, for example.
You could do
"c:\\tc\\bin\\hi.ttcn"
But this is extremely ugly, and your system should accept:
"c:/tc/bin/hi.ttcn"
MS-DOS does not know about long file names, thos including files with extensions longer than 3 characters. Therefore, the CRT provided by Turbo C most probably does not look for the name you are providing, but a truncated one - or something else.
Windows conveniently provides a short (i.e. matching the 8.3 format, most of the time ending in ~1 unless you play with files having the same 8-character prefix) file name for those; one way to discover it is to open a console window and to run "dir /x" in the folder your file is stored.
Find the short name associated to your file and patch it into your C source file.
Edit: Darn, I'll read the comments next time. All credits to j_random_hacker.
Now that you've posted the code, another problem comes to light.
The following line:
fp=fopen("c:\tc\bin\hi.ttcn","r");
Should instead read:
fp=fopen("c:\\tc\\bin\\hi.ttcn","r");
In C strings, the backslash (\) is an escape character that is used to encode special characters (e.g. \n represents a newline character, \t a tab character). To actually use a literal backslash, you need to double it. As it stands, the compiler is actually trying to open a file named "C:<tab>c<backspace>in\hi.ttcn" -- needless to say, no such file exists!

Resources