I want to write to a random output, among which STD_OUTPUT_FILE can be. I want to use
WriteFile, but it does not seem to write anything.
HANDLE outH = GetStdHandle ( STD_OUTPUT_HANDLE );
WriteFile( outH,param, strlen ( param ), &written_b, NULL );
I solved it.
There was a error in redirecting the standard output in which when it should let it be as it was, it was doing something wrong. Do not know yet. I will update my answer.
Your code lacks any form of error-checking. This is common with code copied from a website or Stack Overflow answer, where the error-checking is often omitted for clarity and brevity. But any time you write code yourself, you absolutely must assume that it can fail and write the code to deal with that case. Here, you know it is failing and you still haven't gone back to add the error-checking code to see where that failure is occurring.
Let's add the error-checking code now, referring to the SDK documentation when necessary to see how the API functions you call handle error conditions:
static void ReportError(const TCHAR* errorMsg)
{
MessageBox(NULL, errorMsg, NULL, MB_OK | MB_ICONERROR);
}
int _tmain(int argc, TCHAR* argv[])
{
char param[] = "This is some output.";
DWORD written_b;
HANDLE outH = GetStdHandle(STD_OUTPUT_HANDLE);
if (!outH)
{
ReportError(TEXT("No standard handles associated with this app."));
}
else if (outH == INVALID_HANDLE_VALUE)
{
TCHAR errMsg[100];
wsprintf(errMsg, TEXT("GetStdHandle() failed with error code %lu"), GetLastError());
ReportError(errMsg);
}
else
{
if (!WriteFile(outH, param, strlen(param), &written_b, NULL))
{
TCHAR errMsg[100];
wsprintf(errMsg, TEXT("WriteFile() failed with error code %lu"), GetLastError());
ReportError(errMsg);
}
}
return 0;
}
Now, if something goes wrong, we'll not only know it but we'll know why.
And good thing, because when I run this code on my computer, it works just fine. The problem therefore lies elsewhere in your application in some of the code we haven't seen. The error-handling code will help flush it out.
To write to STDOUT using the calling window/console, you need to link the resulting executable to the console subsystem.
LINK.exe /EDIT /SUBSYSTEM:CONSOLE {your exe name here}
This works with the older VB6 environment, I'm assuming the same executable flags apply to Visual C as well.
Related
For my assignment I have to create a program similar to the -wc unix command which counts words, lines, etc.
I have to read in flags and read in a text file.
I've set up all the flags and now I'm trying to read in a text file. I don't think I'm doing this right.
void readInFile(char** argv, int arg)
{
FILE *myFile;
char c;
myFile = fopen(argv[arg], "r");
if(!myfile)
{
printf("%s not found!", argv[arg]);
exit(EXIT_FAILURE);
}
}
in my main I call the function readInFile() and pass 2 arguments. Argv and the element where the file should be. So assume this to be correct.
I need help with actually opening up the file. I feel like my fopen() is wrong. I'm new to reading/writing files in C. Thanks alot!
I'm going to give you some general advice here.
Usually functions should do a single job. In this case, you are writing a function to read in a single file. So, don't pass a pointer to all the command-line arguments; pass in a single read-only pointer to the name of the file to open. Then in main() select the correct argument and pass that as the argument.
void readInFile(char const *filename)
Now, if this function will be reading in the file and doing nothing else, it needs to return the data somehow. But if this function will be doing the equivalent of wc, maybe it will read the file and print stuff, not return any data to the main() function. Then maybe the name should be improved:
void wordcount(char const *filename)
The actual call to fopen() looks fine to me.
You check for error, and then call exit() immediately. That's one way to do it. Another way to do it is to return an error code from your function, and have the caller (the main() function) check for failure, and handle the error there.
int wordcount(char const *filename)
{
// ... do stuff
if (failed)
return 1; // return nonzero error code on failure
// ... do more stuff
return 0; // success code
}
int main(int argc, char const **argv)
{
char const *filename;
int result;
filename = argv[1];
result = wordcount(filename);
if (result)
{
fprintf(stderr, "unable to open file '%s'\n", filename, result);
exit(result);
}
return 0;
}
For a program this simple, it doesn't matter much. But once you start building larger systems in software, you will be happier if your functions work well together, and part of that is making functions that return error codes rather than terminating your whole program on any error.
Why am I using 0 for the success code, and non-zero for failure? It's a common way to do it. It's easy to test for non-zero, like if (result) and there are many non-zero codes but only one zero, so you can return many different kinds of errors, but there is only one value needed for "success".
Note that instead of calling exit() from main(), you can just use the return statement. When you return 0 from main(), that signals success, and a non-zero value indicates an error. So you could just use return result; from main() if you like.
In my dummy code, I'm just returning 1 as the error code. But actually, when you call fopen() it returns an error code to you, in a global variable called errno. Probably a better option is to make your function return the actual error code as specified in errno. You could even modify the print statement in the main() function print the errno code, or use the strerror() function to turn that error code into a human-readable message.
Your call to fopen is correct, assuming that argv[arg] is a valid string which refers to a file that exists on the filesystem.
There is a small typo in the program snippet. if(!myfile) should prpbably be if(!myFile). With this change, I presume the code should work. Can you please elaborate the error faced by you?
P.S: I tried your program and it seems to work!
I am getting the unable to handle kernel null pointer dereference error while using my kernel module.
Here is what I am trying to do
inputfile = filp_open(kernel_args->infile, O_RDONLY, 0); //Open a file
if(inputfile == NULL) //Check if the file exists
{
printk("\nInput file not found on drive\n");
error = -ENOENT;
goto quit;
}
But the kernel gives me an "oops" when checking for null. I dont know how to avoid it since I am checking for null and doing what I am supposed to do.
Looks like you suspected the wrong pointer, the only pointer that may generate such oops in your code is kernel_args.
few more tips:
- kernel is trusted code, you shouldn't check NULL pointers (unless you are writing kernel module test etc)
- your printk usage is wrong, you are missing the printk log level, for example: printk(KERN_ALERT "Hello world\n");
Check the validity of kernel space arguments.
Like :
if (!kargs)
if(kargs->infile == NULL)
Since filp_open will not return NULL while something went wrong, you should use IS_ERR to check error occurrence.
Like:
if(IS_ERR(inputfile))
goto quit;
I have to a do C program that uses the unix environment. I have already purchased the "Advancing Programming in the Unix Environment" book and it has helped out a lot so far. However, some of my questions have gone unanswered and I'm looking for some help.
I'm trying to write a program that can verify if the first and second arguments entered if a copy program exist. If the first argument does not exist, then an error message and exit must occur. If the second argument does exist, then an overwrite prompt must be displayed. I'm not exactly sure how to verify if a file already exists or not basically.
I have seen a few people saying that you can do (!-e) or something like that to verify the file existing/not existing.
If anyone could help me, I'd really appreciate it.
The access() function is designed to tell you if a file exists (or is readable, writeable or executable).
#include <unistd.h>
int result;
const char *filename = "/tmp/myfile";
result = access (filename, F_OK); // F_OK tests existence also (R_OK,W_OK,X_OK).
// for readable, writeable, executable
if ( result == 0 )
{
printf("%s exists!!\n",filename);
}
else
{
printf("ERROR: %s doesn't exist!\n",filename);
}
in your int main(int argc, char** argv) { block.
if (argc == 3) {
// then there were 3 arguments, the program name, and two parameters
} else if (argc == 2) {
// then prompt for the "second" argument, as the program name and one
// parameter exists
} else {
// just print out the usage, as we have a non-handled number of arguments
}
now if you want to verify that the file exists, that's different than verifying that the program argument exists. Basically attempt to open the file and read from it, but pay close attention to catching the integer error codes and checking them for errors. This will prevent your program from progressing into bits where those critical operations are assumed to have worked.
There is a common, yet misguided conception among new programmers when dealing with files in C. Basically, one really wants to make sure that a specific block of code works (the copying block in your case), so they check, check, and double-check conditions before the block is executed. Check if the file exists, check if it has correct permissions, check that it isn't a directory, etc. My recommendation is that you not do this.
Your copying block should be able to fail properly, just as properly as it should be able to succeed. If it fails, then typically you have all the information necessary to print out a meaningful error message. Should you check first and then act there will always be a small time gap between the check and action, and that time gap will eventually see the file removed or altered after the checks have passed, yet before it is read. Under such a scenario all of the pre-checking code failed to provide any benefit.
Code without benefit is just a nesting ground for future bugs and architectural problems. Don't waste your time writing code that has dubious (or no) benefit. When you suspect that some code you have written has little benefit, you need to restructure your code to put it in the right place. When you suspect that code someone else has written has little benefit, you need to first doubt your suspicions. It is trivially easy to not see the motivations behind a piece of code, and even more so when just starting out in a new language.
Good Luck!
--- code for the weary ---
#include <errorno.h>
#include <stdio.h>
#include <stdlib.h>
extern int errno;
int main(int argc, char** argv) {
// to hold our file descriptor
FILE *fp;
// reset any possible previously captured errors
errno = 0;
// open the file for reading
fp = fopen(argv[1], "r");
// check for an error condition
if ( fp == 0 && errno != 0 ) {
// print the error condition using the system error messages, with the
// additional message "Error occurred while opening file"
perror("Error occurred while opening file.\n");
// terminate the program with a non-successful status
exit(1);
}
}
I wrote a linux device driver and implemented the function device_write like this:
static int device_write(struct file* file,const char* buff,int count, loff * offp)
{
//some implementation
printk("write value %x to card\n",value);
//some implementation
}
I also implement the device_read function and have a printk to print some information in it.
The problem is when I use the read(fd,buff,1) in application program the printk result is displayed but when I use the write(fd,buff,1) there is no printk's result.The device_write function may not be called.What can cause this problem? Have anyone encounter this kind of problem before? Can anybody give me some help and suggestion?
This is only half an answer, but it is too big for a comment.
Are other actions within your device_write function happening?
Do a very simple printk at the top of the device_write function and see if that prints. Something like
static int device_write(struct file* file,const char* buff,int count, loff * offp)
{
printk("%s: %s\n", __FILE__, __func__);
that executes regardless of whatever else happens in the function. If that prints then you can narrow down where to go from there.
If that doesn't work then make sure you are actually setting the function pointer in the device structure. Or maybe your error is in the test application. Are you sure that you've opened up the device with write permissions? That would be an easy mistake to make if you copied code from a program initially written just to test the read functionality.
If I wanted to run a shell command in linux with a c program, I would use
system("ls");
Is there a way I can accomplish this in Wind River vxworks?
I found the below example but I'm wondering do I need to include vxworks header files for this to work? I assume I do, but how do I figure out which one?
Example:
// This function runs a shell command and captures the output to the
// specified file
//
extern int consoleFd;
typedef unsigned int (*UINTFUNCPTR) ();
extern "C" int shellToFile(char * shellCmd, char * outputFile)
{
int rtn;
int STDFd;
int outFileFd;
outFileFd = creat( outputFile, O_RDWR);
printf("creat returned %x as a file desc\n",outFileFd);
if (outFileFd != -1)
{
STDFd=ioGlobalStdGet(STD_OUT);
ioGlobalStdSet(STD_OUT,outFileFd);
rtn=execute(shellCmd);
if (rtn !=0)
printf("execute returned %d \n",outFileFd);
ioGlobalStdSet(STD_OUT,STDFd);
}
close(outFileFd);
return (rtn);
}
I found the code segment below worked for me. For some reason changing the globalStdOut didn't work. Also the execute function did not work for me. But my setting the specific task out to my file, I was able to obtain the data I needed.
/* This function directs the output from the devs command into a new file*/
int devsToFile(const char * outputFile)
{
int stdTaskFd;
int outputFileFd;
outputFileFd = creat( outputFile, O_RDWR);
if (outputFileFd != ERROR)
{
stdTaskFd = ioTaskStdGet(0,1);
ioTaskStdSet(0,1,outputFileFd);
devs();
ioTaskStdSet(0,1,stdTaskFd);
close(outputFileFd);
return (OK);
}
else
return (ERROR);
}
If this is a target/kernel shell (i.e. running on the target itself), then remember that all the shell commands are simply translated to function calls.
Thus "ls" really is a call to ls(), which I believe is declared in dirLib.h
I think that the ExecCmd function is what you are looking for.
http://www.dholloway.com/vxworks/6.5/man/cat2/ExecCmd.shtml
As ever, read the documentation. ioLib.h is required for most of the functions used in that example, and stdio.h of course for printf().
As to the general question of whether you need to include any particular headers for any code to compile, you do need to declare all symbols used, and generally that means including appropriate headers. The compiler will soon tell you about any undefined symbols, either by warning or error (in C89/90 undefined functions are not an error, just a bad idea).