I am trying to write a client/server program in C++ with Visual Studio 2008. So far the project runs does the following:
Run the webserver on cmd prompt - webserver 8080
open web browser - localhost 8080
to open local html file - localhost:8080/demo.html
But now... let's say the client requests for a gif file, then the server should send gif file.
client request for txt file, then the server should send .txt file. Similarly for .html and .xbm files.
I don't know how to do it.. Any help greatly appreciated.
On UNIX systems you'd use the file command: it uses a set of known "magic number" which are used to identify different file types. anda few heuristics to address the remaining files. Most file formats have some sort of identifier embedded, often in the first couple of bytes. Especially text files normally don't have a magic number but use only printable characters instead (with UTF8 and UTF16 being popular, classifying text files became a bit harder).
Once the file type is determined, you'd just set ghe corresponding HTTP header(s).
okay, because we're in the same class, I'll give you a clue :)
In the header part, put some if-else like this:
if(strcmp(type,"html")==0){
(void) sprintf(buff,"Content-Type:text/html\r\n");
(void) send(conn,buff,strlen(buff),0);
}
else if(strcmp(type,"gif")==0){
(void) sprintf(buff,"Content-Type:image/gif\r\n");
(void) send(conn,buff,strlen(buff),0);
}
Got it? And by the way, you need to get the extension (check path using endsWith function), compare the extension with file type then give out the right header. Test it with gif file :) I have it works already :) Going to submit now. Remember to vote up for me :)
Related
when I run this code its only work with visual studio, in online compiler always tell me "cant opening file"
#include <iostream>
#include<fstream>
#include<string>
#include<iomanip>
using namespace std;
ifstream input("C:/Users/ACER/Desktop/words.txt");
if (!input.is_open())
{
cout << "cant opening file";
return 0;
}
An online compiler probably cannot open file on your computer using C++ code since that's not how the web works. It would have to route through some Javascript system, which is possible to create, however it seems the creators did not implement that when setting up their compiler.
You might try using file://C:/Users/ACER/Desktop/words.txt and double checking your path. Web browsers use that file:// thing when accessing local file i.e. if you had a web page on your computer it could be like file://C:/Users/ACER/Documents/index.html or something.
If that doesn't work, it just doesn't have the capability to load or save local files like that.
When you were attempting to use the code on an online compiler, most of the time you are actually compiling the code on their server, instead of on your computer.
What that means is that when you are trying to open "C:/Users/ACER/Desktop/words.txt", you are actually attempting to open a text file that is located on their server. And in most cases, you wouldn't be permitted to lookup any directory other than the one you are in. Even if you were permitted to do that for some reason, the chances they also have that text file on their server in the same location is gonna be really low.
Some comments above mentioned that many online compilers often don't have the facility to manipulate files. One that I often use do have the ability to do so in case you were looking for one: https://replit.com/#Ranoiaetep/IndianredSquigglyPrinters
.Note that the working directory is defaulted as your root directory.
Well this time I'm trying to write a program in C which recover deleted files from a disk, it could be an external disk, I have an idea than i had used before on linux, it is to open the disk as a kind of file and scaning the Headers and file footers of everything within the disk, the point is I'm not sure if there's allow on windows to open a disk as an File, basiclly I have the logic how to develope this program, but I'm not sure how to implement it on windows, anybody can give me a hand with this?.
The code I used on linux to open a disk as a file was:
Edit: That was a sample of what I was using guys, it's just to give you an idea of what I was doing, the correct syntax I used was the next:
direccion = ui->linea->text().toLatin1().constData();
f = fopen(direccion,"rb");
I used QT creator on linux, and direccion variable was a TextField value which contained the file path of the disk through a button function that open a QFileDialog...
could I use it in windows as well?
Thank you before hand..
"The code I used on linux to open a disk as a file was:"
File *f = fopen("E:\", "rb");
I seriously doubt you ever got this code working on any linux system (or windows either).
You'll need to escape the backslash path delimiter, if it's presented in any string literal:
FILE* f = fopen("E:\\", "rb");
// ^
Also all that filesystem path style you are presenting to access a particular disk, is about accessing a windows file path/disk.
No linux file system has notion about drive characters, and the file path delimiter value used is '/', not '\\'.
To recover deleted files, you can't use fopen or fstream::open because the file was deleted. Check the return value from the function or test the stream state.
The way to recover deleted files is:
Get the Master File Table as raw data.
Search for the record containing a string similar to the deleted
filename.
Change the entry in the Master File Table to "undeleted".
Write the Master File Table back to the drive.
The above usually requires platform specific API, which is different on Linux and Windows platforms.
Purpose: I am monitoring file writes in a particular directory on iOS using BSD kernel queues, and poll for file sizes to determine write ends (when the size stops changing). The basic idea is to refresh a folder only after any number of file copies coming from iTunes sync. I have a completely working Objective-C implementation for this but I have my reasons for needing to implement the same thing in C++ only.
Problem: The one thing stopping me is that I can't find a C or C++ API that will get the correct file size during a write. Presumably, one must exist because Objective-C's [NSFileManager attributesOfItemAtPath:] seems to work and we all know it is just calling a C API underneath.
Failed Solutions:
I have tried using stat() and lstat() to get st_size and even st_blocks for allocated block count, and they return correct sizes for most files in a directory, but when there is a file write happening that file's size never changes between poll intervals, and every subsequent file iterated in that directory have a bad size.
I have tried using fseek and ftell but they are also resulting in a very similar issue.
I have also tried modified date instead of size using stat() and st_mtimespec, and the date doesn't appear to change during a write - not that I expected it to.
Going back to NSFileManager's ability to give me the right values, does anyone have an idea what C API call that [NSFileManager attributesOfItemAtPath:] is actually using underneath?
Thanks in advance.
Update:
It appears that this has less to do with in-progress write operations and more with specific files. After closer inspection there are some files which always return a size, and other files that never return a size when using the C API (but will work fine with the Objective-C API). Even creating a copy of the "good" files the C API does not want to give a size for the copy but works fine with the original "good" file. I have both failures and successes with text (xml) files and binary (zip) files. I am using iTunes to add these files to the iPad's app's Documents directory. It is an iPad Mini Retina.
Update 2 - Answer:
Probably any of the above file size methods will work, if your path isn't invisibly trashed, like mine was. See accepted answer on why the path was trashed.
Well this weird behavior turned out to be a problem with the paths, which result in strings that will print normally, but are likely trashed in memory enough that file descriptors sometimes didn't like it (thus only occurring in certain file paths). I was using the dirent API to iterate over the files in a directory and concatenating the dir path and file name erroneously.
Bad Path Concatenation: Obviously (or apparently not-so-obvious at runtime) str-copying over three times is not going to end well.
char* fullPath = (char*)malloc(strlen(dir) + strlen(file) + 2);
strcpy(fullPath, dir);
strcpy(fullPath, "/");
strcpy(fullPath, file);
long sizeBytes = getSize(fullPath);
free(fullPath);
Correct Path Concatenation: Use proper str-concatenation.
char* fullPath = (char*)malloc(strlen(dir) + strlen(file) + 2);
strcpy(fullPath, dir);
strcat(fullPath, "/");
strcat(fullPath, file);
long sizeBytes = getSize(fullPath);
free(fullPath);
Long story short, it was sloppy work on my part, via two typos.
I am trying to extract information from "about:plugins" website when you use Firefox web browser. I want to be able to use the contents of the website in my C++ program. Only way I know how to use content from another location is reading from a file.
What I am trying to do is read the file name and file path for each plugin from about:plugin'
Not sure if I could send this information to a file and then read it from there, but that seems like double work since if it output to file, I could just read it from there.
Needed to know how to extract information from the Firefox website in order to be used in a C++ program.
Just parse the pluginreg.dat file, you can find it in:
C:\Users\xxxxxxx\AppData\Roaming\Mozilla\Firefox\Profiles\xxxxxx.default
To obtain the AppData
char cAppData[MAX_PATH];
if(SHGetSpecialFolderPathA(NULL, cAppData, CSIDL_APPDATA, false))
{
// To obtain the profile name, parse the profiles.ini file in the folder
// ...AppData\Roaming\Mozilla\Firefox
// ...
}
I have some legacy code in one of application which is used for PDF file download (PDF file is around 350-400KB size) and recently we had complains (from around 1% customers) saying PDF download is failing with damaged/corrupted file errors.
Here is snippet of code (C++ application) setting headers for download
String header;
header.append("Content-type: application/force-download\r\n");
header.append("Content-Transfer-Encoding: Binary\r\n");
header.append("Content-length: %d\r\n", filebuf.length());
header.append("Connection: Close\r\n");
header.append("Content-disposition: attachment; filename=%s\r\n\r\n", filename_to_download.chars());
String class and append method is just for an example.
I understand above headers are not the best way to trigger PDF file download (I've simplified headers by having "Content-Type application/octet-stream and Content-Disposition : attachment; filename=example.pdf" and seems like its working for me).
But I am not able to understand why above original code should not work 1% of time.
I was trying to understand browser/adobe combination but seems there is no pattern here, YES one thing few of customers mentioned is when they changed to "chrome browser" it worked most of the times.
Any pointers?
After couple of days of struggle finally figured out whats happening in here.
We are setting content length as size of buffer (pdf file size) in header from our code and sending this data to client but in-between apache module mod_gzip/mod_deflate is compressing data buffer and what reaches client/browser is "Content-Length: 100 bytes" but actual data is say 60-70 bytes.
Not every browser complains about this mismatch but certain browsers treats this as FATAL error and shows message "couldn't download file" (we've seen this issue frequently in Win8/IE10 and Win8/IE11, there could be some other security settings too causing this on browser!).
For the fix, we've removed "Content-Length" from header.