When I simply print the query I get:
one=1&two=2&three=3&four=3&five=3&six=3
Still not working!!!! I am about to go nuts.
#include <stdio.h>
#include <stdlib.h>
int main(void){
char *data;
float prices[] = {1, 2, 3, 4, 5, 6};
int a, b, c, d, e, f;
printf("%s%c%c\n",
"Content-Type:text/html;charset=iso-8859-1",13,10);
printf("<title>Bill</title>\n");
printf("<h3 align=center >Bill</h3>\n");
data = getenv("QUERY_STRING");
if(data == NULL){
printf("<p>Error!</p>");
} else {
printf("%s", data);
sscanf(data, "one=%d&two=%d&three=%d&four=%d&five=%d&six=%d", &a, &b, &c, &d, &e, &f);
}
return 0;
}
Is there an easy and not error prone way to deal with this issue?
Yes; there exist various C libraries, such as cgic and C CGI, that handle common CGI tasks like this one. (If neither of those is to your taste, try Googling "C CGI library" for other options.)
An easy way to parse this string is using sscanf. For this example:
one=2&two=1
you could use:
int one, two;
sscanf(data, "one=%d&two=%d", &one, &two);
More information about sscanf here: http://www.cplusplus.com/reference/clibrary/cstdio/sscanf/
you don't parse anything, so how do you expect to get the values? (Like others said, the most simple way is to use sscanf. note that it will work only if you know the names and order of the arguments, and that you should unescape characters handly after that.)
Your code have some bad things, like if (data==NULL) ... printf("%s",data) (if data may be NULL, why do you print it), and using quantities without allocating space to it.
Related
I have two problems that drive me crazy.
The first one is to integrate JSON in the following code to use JSON as a kind of wrapper around the sqlite statements. This should be for the purpose to display just the entire sql table on a webserver page embedded in HTML. To connect to the database and fetch the table I used sqlite3 and the given functions like sqlite3_open()/sqlite3_close() and so on. I know that sqlite3 has functions to handle JSON as well like json_array()/json_insert() etc. I think this should be a good possible solution to reach my goal. I played around with those functions a bit, but nothing has worked yet. Means there was absolutely no result. Maybe anyone knows how to put the sqlite3 commands/requests in JSON objects to display in a further step those table entries on a simple HTML page. I have to say I`m a absolutely beginer in this section, but read and tried a lot to get into it. But didnt catch it yet.
The second problem is, that the following C code does not execute the while loop to return the rows of my sql table. Output is "Database sucessfull opened unable to fetch data, means it stopps within the last if statement. But I dont know why. Tried to fix it but didnt solve the puzzle yet. The while statement "sqlite3_step(stmt) == SQLITE_ROW" seems to be false, but why? Maybe something is wrong with the stmt pointer.
Hope you could help me. Would be very thankful for every hint to get it work.
C code:
#include "sqlite3.h"
#include <stdio.h>
int main(void) {
sqlite3 *db;
sqlite3_stmt *stmt;
int rc = 0;
rc = sqlite3_open("test.db",&db);
if(rc != SQLITE_OK)
{
printf("Database could not be opened %s \n",sqlite3_errmsg(db));
exit(EXIT_FAILURE);
}
else
{
printf("Database sucessful opened");
}
sqlite3_close(db);
char *sql_stmt = "SELECT * FROM students";
rc = sqlite3_prepare_v2(db, sql_stmt, -1, &stmt, 0);
if(rc != SQLITE_OK)
{
printf("\nUnable to fetch data");
sqlite3_close(db);
return 1;
}
printf("student records\n");
while(sqlite3_step(stmt) == SQLITE_ROW)
{
printf("%s %s %s\n", sqlite3_column_text(stmt, 0), sqlite3_column_text(stmt, 1),
sqlite3_column_text(stmt, 2));
}
sqlite3_finalize(stmt);
sqlite3_close(db);
return 0;
}
I suggest you first figure out why rc = sqlite3_prepare_v2(db, sql_stmt, -1, &stmt, 0); doesn't return an error. Then remove the first sqlite3_close(db); so you are operating on a open database handle.
First, I understand the code is set up for pass by value, I think the question is hypothetical.
Also, this is not homework, it is from a study guide for the final.
This may appear to be a duplicate but the other threads had a lot of emphasis on the code not being set up for anything other than pass by value, so the comments were not very relevant.
I would like to know if b) and c) generate the same answer.
I worked out the problem and have b) and c) with the same result but feel it may be a bit of a trick question, and easy to miss something. Here's the question and the code:
Consider the following program written in C syntax:
void swap( int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
void main()
{
int value = 2, list[5] = {1, 3, 5, 7, 9};
swap(value, list[0]);
swap(list[0], list[1]);
swap(value, list[value]);
}
For each of the following parameter-passing methods, what are all of the values of the variables value and list after each of the three calls to swap?
a) Passed by value
b) Passed by reference
c) Passed by value-result
I'm currently writing my own website and I'm trying to make sure that when someone is making an account the username is unique. I'm doing the back-end in C (since I don't know php/js) and I've been running in a bit of a problem. Right now I'm getting the environment variables in a file newuser.txt (this file has only unique usernames) as such:
fullname=test
description=test
username=test
password=test
I know that at lines 3, 7, 11 etc. in my newusers.txt file I will get my username so I thought of adding all the usernames to another file (which also hosts the incoming data) and then check to see if the incoming username is unique and if it is then I want to add all the data (so fullname, username etc) to newusers.txt. Here's my code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int argc, char *argv[])
{
int currentLine = 1;
char fileLine[100];
int searchLine= 3;
char input[200];
int i=0;
int n = atoi(getenv("CONTENT_LENGTH"));
fgets(input,n+1,stdin); //get the input from the form
printf("Content-Type:text/html\n\n");
printf("<TITLE>Account Creation Query</TITLE>\n");
if (n == 0)
{
printf("<p> Error. Please try again.</p>");
}
FILE *f = fopen("newusers.txt", "ab");
FILE *g = fopen("incoming.txt", "ab");
if (f == NULL)
{
printf("<p> Error in opening the file. Check if the file exists</p>");
printf("<p>Login Page</p>");
printf("<p>Homepage</p>");
}
else
{
while(fgets(fileLine, 100, f)) /*searching for the usernames and adding them to the incoming.txt file */
{
if(searchLine == currentLine)
{
fputs(fileLine, g);
searchLine = searchLine + 4;
}
currentLine++;
}
char *token = strtok(input, "&"); /*tokenizing the incoming data and adding it to the incoming.txt file */
while(token!=NULL)
{
fputs(token, g);
fputs("\n", g);
token = strtok(NULL, "&");
}
}
printf("<p> Account created successfully. You can now login!</p>");
printf("<p>Login Page</p>");
fclose(f);
fclose(g);
return 0;
}
Ideally at this point my incoming.txt file would look like this:
firstname=bla
description=bla
username=bla
password=bla
username=u1
username=u2
username=u3
...
Right now I'm stuck at comparing the incoming username to the other usernames and then copying the data back into newusers.txt. Any help would be appreciated!
use system() call to invoke grep binary to search instead writing searching code in C.
as below
//concat strings to get "grep filename username | cut -d'=' -f2" into cmdstring and then
// read the contents
in=popen(cmdstring, "r");
if(in==NULL)
{
perror("Shell execution error");
exit(EXIT_FAILURE);
}
fgets(buf,3000,in)!=NULL)
here buf contains name of the new user then it is already exist.
otherwise he chose unique name.
I'd strongly recommend that you learn a scripting language for this project. PHP, Perl, Python, Ruby, Javascript… there's plenty of choices, and any one of them will be much more suitable for web programming than C.
That being said, what you need here is a database. Consider using SQLite or Berkeley DB; both are easy to interact with from C, and will allow you to perform lookups and insertions much more easily than would be possible with a flat file (as you're trying to do here).
I'm afraid to ask questions in case it turns out to be stupid... But I tried to search and don't see the same situation.
I'm retrofitting a std::vector into some existing legacy code that is mostly C style. Our next major release which isn't due for a year or two will jettison a lot of the legacy code. But for now, the way we work is, every project gets recompiled for the customer, depending on specs. Some projects are on Visual Studio 2008, some 2010, etc. My added std::vector code I'm working on has no visible problems when compiled with 2013, but, I get crashes within the STL code when running VS 2008 SP1.
The existing code has a struct, and a fixed size array in it:
#define MAX_REMOTE_CONN 75
typedef struct {
int rno;
int adrs;
bool integ_pending;
} RTUref;
typedef struct {
char device[64];
int port;
RTUref RTU[MAX_REMOTE_CONN];
// more stuff...
} Connect_Info;
So, my basic goal is to get rid of the hard coded size limit to the RTU array. So, I have revised it like this:
class{
public:
int rno;
int adrs;
bool integ_pending;
} RTUref;
typedef std::vector <RTUref> RTUlist;
typedef struct {
char device[64];
int port;
RTUlist RTU;
// more stuff...
} Connect_Info;
The Connect_Info structs are allocated using our own memory manager. Don't know much about it other than it is supposed to be more efficient than use malloc() and free(). I'm guessing that the constructor for RTU doesn't get called since the struct it is contained in data allocated by our own memory manager?
Nevertheless, the code where I size the array, put values into the array all at least seem to work okay. But, when I call .clear() I get a crash from within the STL. And as I said, only if I use 2008. If I use 2013, I don't get that crash.
Assuming pct is a pointer to an allocated Connect_Info structure, the the line:
pct->RTU.clear();
Generates a crash on VS 2008. I am able to resize and add elements to the array. And I even tried to add a check that I don't clear unless the size is greater than zero like so:
if (pct->RTU.size() > 0)
pct->RTU.clear();
And I still get the crash on the clear.
So, I made the educated guess that I need to call a constructor. But, I wasn't quite sure of how to do it. But, in the code where the Connect_Info struct is allocated, I tried to add contructor code like this:
pct->RTU = RTUlist();
It compiles. But, I then get a crash in the STL on that line.
I haven't yet tried to build a small contained test program, as I'm not even sure that I will be able to reproduce the problem without our memory manager. But, I will try if that is what I need to do. I thought maybe someone might see obviously what I'm doing wrong. I'm fairly novice to the STL.
A little background: there is a term in C++ called "POD Type" (or "Plain Old Data Type").
There are verbose rules, but basically things that may do special things on allocations, deallocations, or copies are not POD types. The original Connect_Info was a POD type since it didn't do special things at those times and didn't have any non-POD members.
However, since you added a std::vector (which is not a POD type because it has to do special things at allocation, deallocation, copy, etc (because it allocates memory)), Connect_Info is not a POD type.
POD types can be allocated safely with malloc and deallocated with free since they don't do special things. However, non-POD types cannot (except in exceedingly rare cases which you'll first see after several years of programming C++) be allocated like that.
C only has POD types, so malloc is perfectly acceptable. There are a few options you can do:
int main ( ... )
{
Connect_Info * info = new Connect_Info() ;
std::cout << info->port << std::endl ;
delete info ;
}
Or
Connect_Info * makeOne ()
{
void * ptr = malloc ( sizeof(Connect_Info) ) ;
if ( ! ptr ) return 0 ;
return new (ptr) Connect_Info () ; // "In-Place constructor"
}
void deleteOne ( Connect_Info * info )
{
if ( ! ptr ) return ;
info = info->~Connect_Info() ; // manually call its destructor with the weirdest syntax ever
// Note: I'm not 100% sure this call to 'free' is right because the in-place new can return a different pointer, but I don't know how to the get the original back
free ( static_cast<void*>(info) ) ;
}
int main ( ... )
{
Connect_Info * info = makeOne ()
std::cout << info->port << std::endl ;
deleteOne ( info ) ;
}
If you have boost available (or C++11, which you probably don't), this is a MUCH better option (and only uses header components of boost):
boost::shared_ptr<Connect_Info> makeOne ()
{
return boost::make_shared<Connect_Info> () ;
}
int main ( ... )
{
boost::shared_ptr<Connect_Info> info = makeOne ()
std::cout << info->port << std::endl ;
// nothing else: shared_ptr takes care of that for you
}
(If you have C++11, use std::shared_ptr and std::make_shared)
Let us assume that we have the following strings that we need to store in a CUDA array.
"hi there"
"this is"
"who is"
How do we declare a array on the GPU to do this. I tried using C++ strings but it does not work.
Probably the best way to do this is to use structure that is similar to common compressed sparse matrix formats. Store the character data packed into a single piece of linear memory, then use a separate integer array to store the starting indices, and perhaps a third array to store the string lengths. The storage overhead of the latter might be more efficient that storing a string termination byte for every entry in the data and trying to parse for the terminator inside the GPU code.
So you might have something like this:
struct gpuStringArray {
unsigned int * pos;
unsigned int * length; // could be a smaller type if strings are short
char4 * data; // 32 bit data type will improve memory throughput, could be 8 bit
}
Note I used a char4 type for the string data; the vector type will give better memory throughput, but it will mean strings need to be aligned/suitably padded to 4 byte boundaries. That may or may not be a problem depending on what a typical real string looks like in your application. Also, the type of the (optional) length parameter should probably be chosen to reflect the maximum admissible string length. If you have a lot of very short strings, it might be worth using an 8 or 16 bit unsigned type for the lengths to save memory.
A really simplistic code to compare strings stored this way in the style of strcmp might look something like this:
__device__ __host__
int cmp4(const char4 & c1, const char4 & c2)
{
int result;
result = c1.x - c2.x; if (result !=0) return result;
result = c1.y - c2.y; if (result !=0) return result;
result = c1.z - c2.z; if (result !=0) return result;
result = c1.w - c2.w; if (result !=0) return result;
return 0;
}
__device__ __host__
int strncmp4(const char4 * s1, const char4 * s2, const unsigned int nwords)
{
for(unsigned int i=0; i<nwords; i++) {
int result = cmp4(s1[i], s2[i]);
if (result != 0) return result;
}
return 0;
}
__global__
void tkernel(const struct gpuStringArray a, const gpuStringArray b, int * result)
{
int idx = threadIdx.x + blockIdx.x * blockDim.x;
char4 * s1 = a.data + a.pos[idx];
char4 * s2 = b.data + b.pos[idx];
unsigned int slen = min(a.length[idx], b.length[idx]);
result[idx] = strncmp4(s1, s2, slen);
}
[disclaimer: never compiled, never tested, no warranty real or implied, use at your own risk]
There are some corner cases and assumptions in this which might catch you out depending on exactly what the real strings in your code look like, but I will leave those as an exercise to the reader to resolve. You should be able to adapt and expand this into whatever it is you are trying to do.
You have to use C-style character strings char *str. Searching for "CUDA string" on google would have given you this CUDA "Hello World" example as first hit: http://computer-graphics.se/hello-world-for-cuda.html
There you can see how to use char*-strings in CUDA. Be aware that standard C-functions like strcpy or strcmp are not available in CUDA!
If you want an array of strings, you just have to use char** (as in C/C++). As for strcmp and similar functions, it highly depends on what you want to do. CUDA is not really well suited for string operations, maybe it would help if you would provide a little more detail about what you want to do.