I am writing this C code that will store a Key in Registry which points in the current path of the application. Here is the code.
HKEY hKey;
LPCTSTR appPath;
LPCTSTR regPath = TEXT("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
char buffer[300];
GetModuleFileName(NULL,buffer,300);
appPath = buffer;
if(RegOpenKeyEx(HKEY_CURRENT_USER,regPath,0,KEY_ALL_ACCESS,&hKey)== ERROR_SUCCESS)
{
RegSetValueEx(hKey,"storing.exe",0,REG_SZ,appPath,sizeof(appPath));
RegCloseKey(hKey);
}
The problem is that GetModuleFileName() returns the path in that form :
C:\Documents and Settings\User\Desktop\storing.exe
while in the RegSetValueEx() is expected a path in that form :
C:\\Document and Settings\\User\\Desktop\\storring.exe
Is there any way to convert the first path into the second one ?
Tried many ways to replace that string but no one worked.
Thank you.
Try the answer of this question.
This should be enough to solve your problem.
str_replace(appPath, "\", "\\");
Related
I've got a C project that I'm working on and I'm having a problem.
The program reads a string that is echoed by a .php page. It uses this code
to read the data and appoint it to a variable, which get sent to the Commands() function:
LPSTR szBuffer=(LPSTR)chunk+0x1000;
DWORD dwRead;
if (CWA(_HttpSendRequestA, wininet, hHttpRequest, szHeaders, lpstrlenA(szHeaders), szReq, lpstrlenA(szReq)) != 0)
{
CWA(_InternetReadFileA, wininet, hHttpRequest, szBuffer, 0x400, &dwRead);
if (dwRead)
Commands((LPBYTE)szBuffer, dwRead);
}
As you can see the data is sent to the Commands() function, which receives the LPBYTE szBuffer (named "command" in the function) and the DWORD dwRead (named "size" in the function).
In the Commands() function, it's supposed to read the string that it read from the .php page. However, since the data seems to be stored as LPBYTE, I've done a lot of things trying to get that to a char*. When I thought I had finally got it however, I tried outputting it using a MessageBox (to see if it displays the string it should have read). However, this returns me Chinese characters (while the original string should be this:
"TASKci=0C73CCFD206BBD011E7087CE0806E6F6E69630,job=dlex,ti=AD62A5950B76F3812C542C24040EACE9,pr=https,ur=//test.com/test.txt,cl=".
Screenshot of what it returns me: http://prntscr.com/h0p5iw
How the code inside Commands() looks:
BOOL Commands(LPBYTE command, DWORD size) {
LPTSTR x = (LPTSTR)((char*)command);
{
int msgboxID = MessageBox(
NULL,
x,
(LPCWSTR)L"Woop",
MB_ICONWARNING | MB_CANCELTRYCONTINUE | MB_DEFBUTTON2 );
}
CWA(Sleep, kernel32, 100);
return 1; }
I'm new at C (I've only written stuff in C# before) so I am sorry if I am asking any dumb questions, I've really tried my best but I cannot seem to find any solution by myself.
Also, keep in mind that everything except for the stuff inside the Commands() function is not coded by me but by someone who is way more experienced. That code should be fine and I am sure that it is reading the data from the page, it's probably just me screwing up a conversion somewhere.
A narrow string (char*) tends to look like Chinese when you use it somewhere that expects a wide UTF-16 Unicode string.
You cannot just cast the string to change its type, you need to call MultiByteToWideChar.
I was asked to play .wav files using C language, the compiler I'm using is Devcpp.
I was trying to use the function PlaySound() as below:
PlaySound("C:/Users/wavfiles/13.1.wav", NULL, SND_FILENAME);
If I directly input the directory to the function like this, it is able to successfully play the sound.
However, I want to set the directory as a variable. I create a text file with a list of directory and extract the one that I want, then put it into PlaySound() function. Here is part of my code:
FILE *fw;
char addr[1000]
char schapter[50];
while(fgets(addr, 1000, fw) != NULL) {
if((strstr(addr, schapter)) != NULL) {
printf("\n%s", addr);
PlaySound(addr, NULL, SND_FILENAME);
}
}
In this case, the directory is assigned to addr (addr = "C:/Users/wavfiles/13.1.wav") and then I put addr into PlaySound(), but it doesn't work.
I have been stuck on this problem for a long time and cannot move on.
I would really appreciate it if anyone can give me suggestions or solutions.
Thank you.
The string returned by fgets() contains the terminal newline. You'll need to remove that to get the filename.
An easy way to do this is to use strchr() to locate the newline:
while (fgets(addr, 1000, fw) != NULL) {
char *nl = strchr(addr, '\n');
if (nl) *nl = 0;
…
}
I want to delete the folder C:\Users\username\AppData\Roaming\appname when the users uninstall the application appname.
First, I use the following code to get the path C:\Users\username\AppData\Roaming:
TCHAR dir[MAX_PATH];
dir[0] = '\0';
BOOL ok = SHGetSpecialFolderPath(NULL, dir, CSIDL_APPDATA, TRUE);
appname is defined as _T("appname")
The first question is: How to append "appname" to "dir"?
Suppose the above is done. Then I need to use SHFileOperation to delete the non-empty folder C:\Users\username\AppData\Roaming\appname. So I need a double null-terminated string in a SHFILEOPSTRUCT structure. So
How to get a double null-terminated string from the result of the first step? Just append _T("\0\0") to it?
Update: I can use TCHAR *dir2 = lstrcat(dir, appname); to get the path. But when I tried to use TCHAR *dir3 = lstrcat(dir2, _T("\0\0"));, the folder is not deleted. Any number of \0 won't work.
p.s:
If I do the following directly, I got it to work. The problem is that I want to it to be user-independent.
TCHAR path[] = _T("C:\\Users\\username\\AppData\\Roaming\\appname");
memcpy(path + sizeof(path) / sizeof(TCHAR) - 1, _T("\0\0\0"), 3);
For appending paths see PathAppend function.
TCHAR dir[MAX_PATH] = {0};
BOOL ok = SHGetSpecialFolderPath(NULL, dir, CSIDL_APPDATA, TRUE);
PathAppend(dir, _T("appname"));
If you want ensure double null terminating of dir variable:
dir[MAX_PATH - 1] = 0;
dir[MAX_PATH - 2] = 0;
I'm writing a program in C, and I need to known the mime-type of a file.
I have yet searched with Google, and I found that I must include the 'file' UNIX utility in my project.
The source code of file need configure and make. How I can include this in my project? Do I have to crop a part of the source code into a new file.c and file.h?
Do you want to guess the MIME type based on the extension, or do something like file and examine the headers?
To get functionality similar to file, you don't need to include file in your project. Instead, you'll want to use libmagic which file is based on. Unfortunately I'm not aware of a good source of documentation for this, but it's pretty straightforward.
magic_t magic = magic_open(MAGIC_MIME_TYPE);
magic_load(magic, NULL);
char *mime_type = magic_file(magic, "/path/to/file");
magic_close(magic);
Thanks for yours answers and comments.
I solved with this:
const char *w_get_mime(const char *arg, const char *file, int line_no)
{
const char *magic_full;
magic_t magic_cookie;
if(arg == NULL)
w_report_error("called with NULL argument.",file,line_no,__func__,0,1,error);
else if ((magic_cookie = magic_open(MAGIC_MIME) ) == NULL)
report_error("unable to initialize magic library.",0,1,error);
else if (magic_load(magic_cookie, NULL) != 0)
{
magic_close(magic_cookie);
snprintf(globals.err_buff,MAX_BUFF,"cannot load magic database - %s .",magic_error(magic_cookie));
report_error(globals.err_buff,0,1,error);
}
magic_full = magic_file(magic_cookie, arg);
magic_close(magic_cookie);
return magic_full;
}
thanks a lot! :)
I just started working with C & Xcode and I've run into a little difficulty.
All I want to do is read a file from the command line and see the output in the terminal.
I think my problem lies with the path to the file that I want to read in. I'm using a Mac and the file is on my desktop, so the path should be Users/myName/Desktop/words.txt. Is this correct?
This is my code:
#import <Foundation/Foundation.h>
int main (int argc, const char* argv[]){
if(argc == 1){
NSLog(#" you must pass at least one arguement");
return 1;
}
NSLog(#"russ");
FILE* wordFile = fopen(argv[1] , "r");
char word[100];
while (fgets(word,100,wordFile)) {
NSLog(#" %s is %d chars long", word,strlen(word));
}
fclose(wordFile);
return 0;
}//main
If you need the path to a file in OS X, an easy way to get it is to just drag the file into the Terminal.app window where you are typing the command. Voila!
The path to the desktop is /Users/[username]/Desktop/
~/Desktop/ is a user-agnostic way of denoting this, ~ represents the current users home directory. It must be expanded using a method like stringByExpandingTildeInPath
Not sure about using C# (I've never used it on Mac OS X), but in Objective-C/Cocoa, you would do..
// Get array with first index being path to desktop
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES);
// Get the first element
NSString *desktopPath = [paths objectAtIndex:0];
// Append words.txt to path
NSString *theFilePath = [desktopPath stringByAppendingPathComponent:#"words.txt"];
NSLog(#"%#", theFilePath);
This is the most robust way of getting the Desktop path, as a user could technically move their Desktop folder else where (although this is pretty unlikely). Another valid option is to use the NSString method stringByExpandingTildeInPath:
NSString *desktop = [#"~/Desktop" stringByExpandingTildeInPath];
NSString *theFile = [desktop stringByAppendingPathComponent:#"words.txt"]
As I said, both those are in Objective-C, but it shouldn't be hard to translate to C#, assuming you can get at the Cocoa libraries.
The code you posted works correctly:
dbr:.../build/Debug $ ./yourcode ~/Desktop/words.txt
yourcode[2106:903] russ
yourcode[2106:903] this is words.txt is 17 chars long
Your terminal automatically expands the ~/ tilda path
Close... it's
/{Volume}/Users/myName/Desktop/words.txt
... where {Volume} is the name of your hard drive. You can also try using:
~/Desktop/words.txt
... where ~ is understood to mean "your home directory", but this might not resolve correctly.
(Note - this appears to be a C question, not a C# question)
Actually, you can do:
/Users/myName/Desktop/words.txt
You don't have to give the path to the volume.
However, to get the full path in C you'd do something like:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char *home, *fullPath;
home = getenv("HOME");
fullPath = strcat(home, "/Desktop/words.txt");
The issue you're running into with passing the filename as an argument is that you need to set the current working directory to the place where the file exists.