I have an issue with trying to check if a file exists and reading it if it exists.
My code:
use std::{env, fs};
use std::fs::{File, read};
use std::path::Path;
use std::process::exit;
let arg = env::args().next().expect("Please open a file via the command line!");
let path = Path::new(
&arg
);
if !path.exists() {
error!("The specified path does not exist!");
exit(101);
}
let file = read(path).expect("Could not read file!");
let content = String::from_utf8(file).expect("The file does not contain valid characters!");
Run the program like this ./program.exe a_vali_file_path.txt
Expectation:
If you run the program with a valid file path as the first argument, the program will check if it exists. If it does, the program reads the file content and just returns.
What actually happened:
The program doesn't even really check for the file (it does not panic, even if the path is not valid) and if it tries to read it prints a bunch of bytes into the console followed by the error
error: Utf8Error { valid_up_to: 2, error_len: Some(1) } }.
This behavior occurs if the file exists or not.
env::args.next() references the executable, which doesn't contain UTF-8 bytes. If you want to point to the next argument you must use another .next() call, or better yet use a Vector to store your args.
Example of a vector being used to store args ->
fn main() {
let args: Vec<String> = env::args().collect()
...
}
To solve it your way:
fn main() {
let args = env::args()
args.next() //Points to executable (argv[0])
args.next() //Points to file (argv[1])
}
As you can see the second solution is not very elegant, but hey, to each their own.
Related
#include <Windows.h>
int main(){
printf("Enter name of program. \n");
char prog[300];
scanf("%s", prog);
HMODULE hModule = GetModuleHandleW((LPCWSTR)prog);
if (hModule){
IMAGE_DOS_HEADER* pIDH = (IMAGE_DOS_HEADER*)hModule;
IMAGE_NT_HEADERS* pNTH =(IMAGE_NT_HEADERS*)((BYTE*)pIDH + pIDH->e_lfanew);
IMAGE_OPTIONAL_HEADER pOPH = (IMAGE_OPTIONAL_HEADER)pNTH->OptionalHeader;
IMAGE_DATA_DIRECTORY* pIDD = (IMAGE_DATA_DIRECTORY*)pOPH.DataDirectory;
printf("%x", pIDD->VirtualAddress);
}
else {
printf("Error");
}
return 0;
}
That's my basic script for now only to check if I get into the IMAGE_DATA_DIRECTORY.
My goal is to print every dll and all of it's imported functions of a certain running process - GetModuleHandleA / W.
Every call its returning null - printing "Error" as I checked, excluding the empty call in which it prints '0' for some reason..
Besides the obvious (LPCWSTR)prog casting bug, GetModuleHandle is never going to work because it only handles modules in the current process.
Call CreateToolhelp32Snapshot to get a list of all processes and then call CreateToolhelp32Snapshot again to get the modules of a specific process. Note that you cannot read the DOS/NT headers of a remote process directly, you would have to use ReadProcessMemory.
DataDirectory is an array, you have to specify the directory you are interested in (resource, import, export etc.).
I am using libxml in my iOS Swift project. To debug, I need to call the following C function from Swift:
void xmlDebugDumpString (FILE * output, const xmlChar * r)
However, I don't know how to create the FILE * output pointer in Swift.
I tried the following code:
let debugDoc: UnsafeMutablePointer<FILE>
debugDoc = fopen(debugDocURL.absoluteString, "w")
xmlDebugDumpNode(debugDoc, str)
The code compiled fine but gives the following runtime error
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
The problem is the wrong usage of absoluteString, so that fopen()
fails and returns nil. The correct way to create a C string from an URL is withUnsafeFileSystemRepresentation:
guard let debugFile = debugDocURL.withUnsafeFileSystemRepresentation( { fopen($0, "w") }) else {
// Could not open file ...
}
Now you can write to the file
xmlDebugDumpNode(debugFile, ...)
and eventually close it:
fclose(debugFile)
An alternative option is to dump the debug output to the (predefined)
“standard error” file:
xmlDebugDumpNode(stderr, ...)
My goal is to search the file line by line until it finds a variable declaration in the format of varName = varValue. Count up the bytes to the beginning of that line, then replace that line with the same varName but a new value.
This is a very simple configuration file handler, I'm writing it from scratch to avoid any dependencies. The reason I'm doing it this way and not just dumping a string[string] associative array is because I want to preserve comments. I also wish to refrain from reading the entire file into memory, as it has the potential to get large.
This is the code I have written, but nothing happens and the file remains unchanged when using setVariable.
import std.stdio: File;
import std.string: indexOf, strip, stripRight, split, startsWith;
import std.range: enumerate;
ptrdiff_t getVarPosition(File configFile, const string varName) {
size_t countedBytes = 0;
foreach (line, text; configFile.byLine().enumerate(1)) {
if (text.strip().startsWith(varName))
return countedBytes;
countedBytes += text.length;
}
return -1;
}
void setVariable(File configFile, const string varName, const string varValue) {
ptrdiff_t varPosition = getVarPosition(configFile, varName);
if (varPosition == -1)
return; // For now, just return. This variable doesn't exist.
// Will handle this later, it needs to append to the bottom of the file.
configFile.seek(varPosition);
configFile.write(varName ~ " = " ~ varValue);
}
There's a few parts of your code missing, which makes diagnosis hard. The most important question may be 'How do you open your config file?'. This code does what I expect it to:
unittest {
auto f = File("foo.txt", "r+");
setVariable(f, "var3", "foo");
f.flush();
}
That is, it finds the line starting with "var3", and replaces part of the file with the new value. However, your getVarPosition function doesn't count newlines, so the offset is wrong. Also, consider what happens when the new varValue is a different length from the old value. If you have "var = hello world", and call setVariable(f, "var", "bye"), you'll end up with "var = byelo world". If it's longer than the existing value, it will overwrite the next variable(s).
I want to make a program (network server-client).
One of the specification for this program is next:
The server will receive the sent packages and save it into a file, with a unique name (generated by the server at the moment the transfer starts.
Ex __tf_"unique_random_string".txt
I made a function that returns a pointer to a "unique" string created.
The problem is: If i stop the server and then start it again it will generate the same names.
Ex:this file names were generated and then i stopped the server.
__ft_apqfwk.txt
__ft_arzowk.txt
__ft_cdyggx.txt
I start it again and i try to generate 3 file names. Them will be the same.
Sorry for my english. I'm still learning it.
My function to generate this "unique string" is:
char *create_random_name(void)
{
const char charset[] = "abcdefghijklmnopqrstuvwxyz";
char *file_name;
int i=0;
int key;
if((file_name = malloc(16 * sizeof ( char )) ) == NULL)
{
printf("Failed to alloc memory space\n");
return NULL;
}
strcpy(file_name,"__ft_");
for(i=5 ; i<11 ; i++)
{
key = rand() % (int)(sizeof(charset)-1);
file_name[i]=charset[key];
}
strcat(file_name,".txt");
file_name[15] = '\0';
return file_name;
}
One option is saving to a file the names that have been used, and using them as a checklist. You also want to seed rand with something like srand(time(NULL)).
another is ignoring the randomisation, and just going in order, e.g. aaa, aab aac...aba ,abb etc. Again, save where your cycle is up to on a file.
Your question seems a little bit unclear but if you want to generate a unique string there are a couple of things you can consider:
Get System timestamp ( yyyy-MM-dd-HH-mm-ss-fff-tt)
Use Random function to generate a random number
Combine this with your function and I am sure you will get a unique string.
Hope it helps !
If it's available, you could avoid manually generating random names that might collide and let the system do it for you (and handle collision resolution by creating a new name) by using mkstemps. This is also safer because it opens the file for you, removing the risk of a random name being generated, verified to be unique, then trying to open it and discovering another thread/process raced in and created it.
char name[] = "/path/to/put/files/in/__ft_XXXXXX.txt";
int fd = mkstemps(name, strlen(".txt"));
if (fd == -1) { ... handle error ... }
After mkstemps succeeds, name will hold the path to the file (it's mutated in place, replacing the XXXXXX string), and fd will be an open file descriptor to that newly created file; if you need a FILE*, use fdopen to convert to a stdio type.
Before calling rand(),--- once and only once---, call srand(time()) to initialize the random number generator.
Before settling on any specific file name, call stat() to assure that file name does not already exist.
I am wondering where I can find C tutorial/example of using AntLR. All I found is using Java language.
I am focusing to find a main function which use the parser and lexer generated by AntLR.
Take a look at this document
And here is an example:
// Example of a grammar for parsing C sources,
// Adapted from Java equivalent example, by Terence Parr
// Author: Jim Idle - April 2007
// Permission is granted to use this example code in any way you want, so long as
// all the original authors are cited.
//
// set ts=4,sw=4
// Tab size is 4 chars, indent is 4 chars
// Notes: Although all the examples provided are configured to be built
// by Visual Studio 2005, based on the custom build rules
// provided in $(ANTLRSRC)/code/antlr/main/runtime/C/vs2005/rulefiles/antlr3.rules
// there is no reason that this MUST be the case. Provided that you know how
// to run the antlr tool, then just compile the resulting .c files and this
// file together, using say gcc or whatever: gcc *.c -I. -o XXX
// The C code is generic and will compile and run on all platforms (please
// report any warnings or errors to the antlr-interest newsgroup (see www.antlr.org)
// so that they may be corrected for any platform that I have not specifically tested.
//
// The project settings such as additional library paths and include paths have been set
// relative to the place where this source code sits on the ANTLR perforce system. You
// may well need to change the settings to locate the includes and the lib files. UNIX
// people need -L path/to/antlr/libs -lantlr3c (release mode) or -lantlr3cd (debug)
//
// Jim Idle (jimi cut-this at idle ws)
//
// You may adopt your own practices by all means, but in general it is best
// to create a single include for your project, that will include the ANTLR3 C
// runtime header files, the generated header files (all of which are safe to include
// multiple times) and your own project related header files. Use <> to include and
// -I on the compile line (which vs2005 now handles, where vs2003 did not).
//
#include <C.h>
// Main entry point for this example
//
int ANTLR3_CDECL
main (int argc, char *argv[])
{
// Now we declare the ANTLR related local variables we need.
// Note that unless you are convinced you will never need thread safe
// versions for your project, then you should always create such things
// as instance variables for each invocation.
// -------------------
// Name of the input file. Note that we always use the abstract type pANTLR3_UINT8
// for ASCII/8 bit strings - the runtime library guarantees that this will be
// good on all platforms. This is a general rule - always use the ANTLR3 supplied
// typedefs for pointers/types/etc.
//
pANTLR3_UINT8 fName;
// The ANTLR3 character input stream, which abstracts the input source such that
// it is easy to provide input from different sources such as files, or
// memory strings.
//
// For an ASCII/latin-1 memory string use:
// input = antlr3NewAsciiStringInPlaceStream (stringtouse, (ANTLR3_UINT64) length, NULL);
//
// For a UCS2 (16 bit) memory string use:
// input = antlr3NewUCS2StringInPlaceStream (stringtouse, (ANTLR3_UINT64) length, NULL);
//
// For input from a file, see code below
//
// Note that this is essentially a pointer to a structure containing pointers to functions.
// You can create your own input stream type (copy one of the existing ones) and override any
// individual function by installing your own pointer after you have created the standard
// version.
//
pANTLR3_INPUT_STREAM input;
// The lexer is of course generated by ANTLR, and so the lexer type is not upper case.
// The lexer is supplied with a pANTLR3_INPUT_STREAM from whence it consumes its
// input and generates a token stream as output.
//
pCLexer lxr;
// The token stream is produced by the ANTLR3 generated lexer. Again it is a structure based
// API/Object, which you can customise and override methods of as you wish. a Token stream is
// supplied to the generated parser, and you can write your own token stream and pass this in
// if you wish.
//
pANTLR3_COMMON_TOKEN_STREAM tstream;
// The C parser is also generated by ANTLR and accepts a token stream as explained
// above. The token stream can be any source in fact, so long as it implements the
// ANTLR3_TOKEN_SOURCE interface. In this case the parser does not return anything
// but it can of course specify any kind of return type from the rule you invoke
// when calling it.
//
pCParser psr;
// Create the input stream based upon the argument supplied to us on the command line
// for this example, the input will always default to ./input if there is no explicit
// argument.
//
if (argc < 2 || argv[1] == NULL)
{
fName =(pANTLR3_UINT8)"./input"; // Note in VS2005 debug, working directory must be configured
}
else
{
fName = (pANTLR3_UINT8)argv[1];
}
// Create the input stream using the supplied file name
// (Use antlr3AsciiFileStreamNew for UCS2/16bit input).
//
input = antlr3AsciiFileStreamNew(fName);
// The input will be created successfully, providing that there is enough
// memory and the file exists etc
//
if ( input == NULL)
{
fprintf(stderr, "Failed to open file %s\n", (char *)fName);
exit(1);
}
// Our input stream is now open and all set to go, so we can create a new instance of our
// lexer and set the lexer input to our input stream:
// (file | memory | ?) --> inputstream -> lexer --> tokenstream --> parser ( --> treeparser )?
//
lxr = CLexerNew(input); // CLexerNew is generated by ANTLR
// Need to check for errors
//
if ( lxr == NULL )
{
fprintf(stderr, "Unable to create the lexer due to malloc() failure1\n");
exit(1);
}
// Our lexer is in place, so we can create the token stream from it
// NB: Nothing happens yet other than the file has been read. We are just
// connecting all these things together and they will be invoked when we
// call the parser rule. ANTLR3_SIZE_HINT can be left at the default usually
// unless you have a very large token stream/input. Each generated lexer
// provides a token source interface, which is the second argument to the
// token stream creator.
// Note that even if you implement your own token structure, it will always
// contain a standard common token within it and this is the pointer that
// you pass around to everything else. A common token as a pointer within
// it that should point to your own outer token structure.
//
tstream = antlr3CommonTokenStreamSourceNew(ANTLR3_SIZE_HINT, TOKENSOURCE(lxr));
if (tstream == NULL)
{
fprintf(stderr, "Out of memory trying to allocate token stream\n");
exit(1);
}
// Finally, now that we have our lexer constructed, we can create the parser
//
psr = CParserNew(tstream); // CParserNew is generated by ANTLR3
if (psr == NULL)
{
fprintf(stderr, "Out of memory trying to allocate parser\n");
exit(ANTLR3_ERR_NOMEM);
}
// We are all ready to go. Though that looked complicated at first glance,
// I am sure, you will see that in fact most of the code above is dealing
// with errors and there isn't really that much to do (isn't this always the
// case in C? ;-).
//
// So, we now invoke the parser. All elements of ANTLR3 generated C components
// as well as the ANTLR C runtime library itself are pseudo objects. This means
// that they are represented as pointers to structures, which contain any
// instance data they need, and a set of pointers to other interfaces or
// 'methods'. Note that in general, these few pointers we have created here are
// the only things you will ever explicitly free() as everything else is created
// via factories, that allocated memory efficiently and free() everything they use
// automatically when you close the parser/lexer/etc.
//
// Note that this means only that the methods are always called via the object
// pointer and the first argument to any method, is a pointer to the structure itself.
// It also has the side advantage, if you are using an IDE such as VS2005 that can do it
// that when you type ->, you will see a list of tall the methods the object supports.
//
psr->translation_unit(psr);
// We did not return anything from this parser rule, so we can finish. It only remains
// to close down our open objects, in the reverse order we created them
//
psr ->free (psr); psr = NULL;
tstream ->free (tstream); tstream = NULL;
lxr ->free (lxr); lxr = NULL;
input ->close (input); input = NULL;
return 0;
}
contrapunctus.net/blog/2012/antlr-c a simple google would suffice. Note however, the example is C++ I don't think ANTLR supports PURE C – Aniket Jan 1 at 1:56