How to reverse a structure in text file with C? - reverse

I have an exercise and I don't know how to solve it well!
I want write a C program that give from user the information of a student and then save it to file A.txt. After that reverse the first name, last name and student number and save it to file B.txt.
For example:
john
lopez
123456
It changes to:
nhoj
zepol
654321
#include <stdio.h>
#include <stdlib.h>
#define SIZE 50
struct student {
char fname[SIZE];
char lname[SIZE];
char num[SIZE];
}st;
int main()
{
FILE *in, *out;
char ch;
int tmp=0,flag=0,i;
printf("INPUT First name: ");
scanf("%s", &st.fname);
printf("INPUT Last name: ");
scanf("%s", &st.lname);
printf("INPUT personal num: ");
scanf("%s", &st.num);
in= fopen("A.txt", "w");
fputs(st.fname, in);
fputs(st.lname, in);
fputs(st.num, in);
fclose(in);
in= fopen("A.txt", "r");
out=fopen("B.txt", "w");
fgets(st.fname, strlen(st.fname)+1,in);
strrev(st.fname);
fputs(st.fname, out);
printf("\n%s", st.fname);
fgets(st.lname, strlen(st.lname)+1, in);
strrev(st.lname);
fputs(st.lname, out);
printf("\n%s", st.lname);
fgets(st.num, strlen(st.num)+1, in);
strrev(&st.num);
fputs(st.num, out);
printf("\n%d", st.num);
fclose(in);
fclose(out);
return 0;
}

If you want to copy the data to a file, then you first need to put the data in some dynamic memory allocation and then after reversing the content required in dynamic memory, you need to copy it into your file.

this is the program to reverse the each word in given string
#include
#include
void reverse_string(char*);
void reverse_words(char*);
int main() {
char a[100];
gets(a);
reverse_words(a);
printf("%s\n", a);
return 0;
}
void reverse_words(char *s) {
char b[100], *t, *z;
int c = 0;
t = s;
while(*t) { //processing complete string
while(*t != ' ' && *t != '\0') { //extracting word from string
b[c] = *t;
t++;
c++;
}
b[c] = '\0';
c = 0;
reverse_string(b); // reverse the extracted word
z = b;
while (*z) { //copying the reversed word into original string
*s = *z;
z++;
s++;
}
while (*s == ' ') { // skipping space(s)
s++;
}
/*
* You may use if statement in place of while loop if
* you are assuming only one space between words. If condition is
* used because null terminator can also occur after a word, in
* that case we don't want to increment pointer.
* if (*s == ' ') {
* s++;
* }
*/
t = s; // pointing to next word
}
}
/*
* Function to reverse a word.
*/
void reverse_string(char *t) {
int l, c;
char *e, s;
l = strlen(t);
e = t + l - 1;
for (c = 0; c < l/2; c++) {
s = *t;
*t = *e;
*e = s;
t++;
e--;
}
}

Then you can try using fputc, i.e., reading char by char along with a loop to get your data line by line as 3 lines.
char *ch;
for(i=0;st.fname[i];i++)
{
ch=getc(st.fname[i]);
fputc(ch,in);
}
repeat the same even for st.lname and st.num

Related

How is it possible to compile code from code

I want to experiment with the programs that write programs in C code, and i want to use construction like following:
int main() {
char* srcCode="int f(int x) { return x+42; }";
int (*compiledFun)(int) = compile(srcCode);
printf("result=%d", (*compiledFun)(123));
return 0;
}
Desired output should be printed "result=165".
My question is about compile() function. I may try to put srcCode in a file, then invoke external compiler, like gcc, then try to read produced binary, probably fix some addresses, and so to fill the compiledFun memory. But I feel like that would be a very inefficient stub. Is there any way to compile a program from within a program, directly from memory to memory? Maybe some library or a subset that can be ripped off gcc sources, responsible for producting binary code from source text?
That may be important addition, all source code that should be compiled is a function that takes arguments and returns. It will not call any external libraries and function like printf, but only do some calculations and return.
Use libtcc an in-memory C compiler from TinyC.
A complete example from here https://github.com/TinyCC/tinycc/blob/mob/tests/libtcc_test.c
/*
* Simple Test program for libtcc
*
* libtcc can be useful to use tcc as a "backend" for a code generator.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "libtcc.h"
/* this function is called by the generated code */
int add(int a, int b)
{
return a + b;
}
/* this strinc is referenced by the generated code */
const char hello[] = "Hello World!";
char my_program[] =
"#include <tcclib.h>\n" /* include the "Simple libc header for TCC" */
"extern int add(int a, int b);\n"
"#ifdef _WIN32\n" /* dynamically linked data needs 'dllimport' */
" __attribute__((dllimport))\n"
"#endif\n"
"extern const char hello[];\n"
"int fib(int n)\n"
"{\n"
" if (n <= 2)\n"
" return 1;\n"
" else\n"
" return fib(n-1) + fib(n-2);\n"
"}\n"
"\n"
"int foo(int n)\n"
"{\n"
" printf(\"%s\\n\", hello);\n"
" printf(\"fib(%d) = %d\\n\", n, fib(n));\n"
" printf(\"add(%d, %d) = %d\\n\", n, 2 * n, add(n, 2 * n));\n"
" return 0;\n"
"}\n";
int main(int argc, char **argv)
{
TCCState *s;
int i;
int (*func)(int);
s = tcc_new();
if (!s) {
fprintf(stderr, "Could not create tcc state\n");
exit(1);
}
/* if tcclib.h and libtcc1.a are not installed, where can we find them */
for (i = 1; i < argc; ++i) {
char *a = argv[i];
if (a[0] == '-') {
if (a[1] == 'B')
tcc_set_lib_path(s, a+2);
else if (a[1] == 'I')
tcc_add_include_path(s, a+2);
else if (a[1] == 'L')
tcc_add_library_path(s, a+2);
}
}
/* MUST BE CALLED before any compilation */
tcc_set_output_type(s, TCC_OUTPUT_MEMORY);
if (tcc_compile_string(s, my_program) == -1)
return 1;
/* as a test, we add symbols that the compiled program can use.
You may also open a dll with tcc_add_dll() and use symbols from that */
tcc_add_symbol(s, "add", add);
tcc_add_symbol(s, "hello", hello);
/* relocate the code */
if (tcc_relocate(s, TCC_RELOCATE_AUTO) < 0)
return 1;
/* get entry symbol */
func = tcc_get_symbol(s, "foo");
if (!func)
return 1;
/* run the code */
func(32);
/* delete the state */
tcc_delete(s);
return 0;
}

Arduino + MySql + MySqlIO error when compiling

I'm trying to make this project. When i try to compile this code:
#include <mysql.h>
char *host, *user, *pass, *db;
int isconnected = 0;
void setup()
{
Serial.begin(9600);
host = "localhost";
user = "root";
pass = "";
db = "arduino";
isconnected = mysql_connect(host,user,pass,db);
if(isconnected){
Serial.print("Connected to ");
Serial.println(host);
}
else{
Serial.println("Connection failed.");
}
mysql_close();
}
void loop(){}
Maybe problem is with libraries or Arduino IDE. I get these errors and warnings:
C:\Users\Mateusz\Documents\Arduino\libraries\mysql\examples\ConnectToMysql\ConnectToMysql.ino:
In function 'void setup()':
C:\Users\Mateusz\Documents\Arduino\libraries\mysql\examples\ConnectToMysql\ConnectToMysql.ino:30:7:
warning: deprecated conversion from string constant to 'char*'
[-Wwrite-strings]
host = "localhost";
^
C:\Users\Mateusz\Documents\Arduino\libraries\mysql\examples\ConnectToMysql\ConnectToMysql.ino:31:7:
warning: deprecated conversion from string constant to 'char*'
[-Wwrite-strings]
user = "root";
^
C:\Users\Mateusz\Documents\Arduino\libraries\mysql\examples\ConnectToMysql\ConnectToMysql.ino:32:7:
warning: deprecated conversion from string constant to 'char*'
[-Wwrite-strings]
pass = "";
^
C:\Users\Mateusz\Documents\Arduino\libraries\mysql\examples\ConnectToMysql\ConnectToMysql.ino:33:5:
warning: deprecated conversion from string constant to 'char*'
[-Wwrite-strings]
db = "arduino";
^
C:\Users\Mateusz\Documents\Arduino\libraries\mysql\mysql.cpp: In
function 'String mysql_result_query(String, String)':
C:\Users\Mateusz\Documents\Arduino\libraries\mysql\mysql.cpp:67:10:
error: converting to 'String' from initializer list would use explicit
constructor 'String::String(int, unsigned char)'
return 0;
^
C:\Users\Mateusz\Documents\Arduino\libraries\mysql\mysql.cpp:71:10:
error: converting to 'String' from initializer list would use explicit
constructor 'String::String(int, unsigned char)'
return 0;
^
exit status 1
Edit:
There is library mysql.cpp.
#include "mysql.h"
int mysql_connect(char *host, char *user, char *pass, char *db){
Serial.print("host=");
Serial.println(host);
Serial.print("user=");
Serial.println(user);
Serial.print("pass=");
Serial.println(pass);
Serial.print("db=");
Serial.println(db);
Serial.println("mysql_connect()");
int x = Serial.read();
if(x == '-')
return 0;
while( x <= 0){
x = Serial.read();
if(x == '-')
return 0;
}
return x-48;
}
int is_mysql(){
Serial.print("is_mysql()");
int x = Serial.read();
if(x == '-')
return 0;
while( x <= 0){
x = Serial.read();
if(x == '-')
return 0;
}
return x-48;
}
void mysql_close(){
Serial.println("mysql_close()");
}
int mysql_query(char *query){
Serial.print("query=");
Serial.println(query);
int x = Serial.read();
if(x == '-' || x == '0')
return 0;
while( x <= 0){
x = Serial.read();
if(x == '-' || x == '0')
return 0;
}
return x-12;
}
String mysql_result_query(String query, String field){
String res = "";
String q = "query=" + query + "&field=" + field;
Serial.println(q);
res = Serial.readString();
if(res == "-")
return 0;
while(res.length() <= 0){
res = Serial.readString();
if(res == "-")
return 0;
}
return res;
}
And there is mysql.h:
#ifndef mysql_h
#define mysql_h
#include "Arduino.h"
int mysql_connect(char *, char *, char *, char *);
void mysql_close();
int is_mysql();
int mysql_query(char *);
String mysql_result_query(String, String);
#endif
I don't know how to solve this. I could'nt find any solutions. Sorry for my english :)
You need to initialize your variables at the beginning.
Try this:
#include <mysql.h>
char *host = "localhost", *user="root", *pass="", *db="arduino";
int isconnected = 0;
void setup()
{
Serial.begin(9600);
isconnected = mysql_connect(host,user,pass,db);
if(isconnected){
Serial.print("Connected to ");
Serial.println(host);
}
else{
Serial.println("Connection failed.");
}
mysql_close();
}
void loop(){}
The erros are comming from your mysql_result_query function. You are returning 0 for a function that returns a String.
Try this.
String mysql_result_query(String query, String field){
String res = "";
String q = "query=" + query + "&field=" + field;
Serial.println(q);
res = Serial.readString();
if(res == "-")
return "";
while(res.length() <= 0){
res = Serial.readString();
if(res == "-")
return "";
}
return res;
}
Here I'm returning an empty string. You can check it later with the length() method.

Thrust: selectively move elements to another vector

I'm trying to figure out the best way to do the following using Thrust: vector A has a million floats, they have some particular order. I want to move to vector B every element x in A for which x>7.0 such that the order of elements is maintain in both vectors A and B. Importantly, only a tiny fraction of elements need be moved. Efficiency is more important for my code than elegance.
My idea was to use thrust::copy_if from A to B and then thrust::remove_if on A. But I don't know the exact number of elements to be copy, and since apparently the memory for B must be allocated in advance, another counting operation is necessary. An inelegant way to skip the counting operation is to pre-allocate "enough" memory for vector B.
Using thrust::remove_copy_if has much the same problems: you need to allocate memory for B in advance, and also it doesn't actually remove anything from A so another thrust::remove_if is required anyway.
Another idea I had was to use thrust::stable_sort with some custom-made comparison functor, to push all elements I want out to the end of A, and then somehow figure out how many there are and thrust::copy them to B. This also looks pretty inelegant...
You're on the right track with thrust::copy_if. Just allocate two more buffers of the same size as the first one. Then copy_if > 7.0f to the first one and copy_if <= 7.0f to the second one. Allocating buffers of the same size as the original buffer is fine as long as you know there's room, and 1 million floats only takes up 4MB.
Edit:
I did a performance comparison of the copy_if and stable_partition approaches. On my card, a GTX660, stable_partition took around 150% as long as copy_if for "split" values of 0.1f, 0.5f and 0.9f. I added tests to ensure that both methods are stable (maintain the order of the values).
#include <cuda.h>
#include <curand.h>
#include <thrust/device_vector.h>
#include <thrust/host_vector.h>
#include <thrust/copy.h>
#include <thrust/partition.h>
#include <iostream>
#include <cassert>
#define CHECK_CUDA_CALL(x) do { if((x)!=cudaSuccess) { \
printf("Error at %s:%d\n",__FILE__,__LINE__);\
return EXIT_FAILURE;}} while(0)
#define CHECK_CURAND_CALL(x) do { if((x)!=CURAND_STATUS_SUCCESS) { \
printf("Error at %s:%d\n",__FILE__,__LINE__);\
return EXIT_FAILURE;}} while(0)
#define SPLIT 0.1f
struct is_low
{
__host__ __device__ bool operator()(const float x)
{
return x <= SPLIT;
}
};
struct is_high
{
__host__ __device__ bool operator()(const float x)
{
return x > SPLIT;
}
};
class EventTimer {
public:
EventTimer() : mStarted(false), mStopped(false) {
cudaEventCreate(&mStart);
cudaEventCreate(&mStop);
}
~EventTimer() {
cudaEventDestroy(mStart);
cudaEventDestroy(mStop);
}
void start(cudaStream_t s = 0) {
cudaEventRecord(mStart, s);
mStarted = true;
mStopped = false;
}
void stop(cudaStream_t s = 0) {
assert(mStarted);
cudaEventRecord(mStop, s);
mStarted = false;
mStopped = true;
}
float elapsed() {
assert(mStopped);
if (!mStopped) return 0;
cudaEventSynchronize(mStop);
float elapsed = 0;
cudaEventElapsedTime(&elapsed, mStart, mStop);
return elapsed;
}
private:
bool mStarted, mStopped;
cudaEvent_t mStart, mStop;
};
int main(int argc, char *argv[])
{
const size_t n = 1024 * 1024 * 50;
// Create prng
curandGenerator_t gen;
CHECK_CURAND_CALL(curandCreateGenerator(&gen, CURAND_RNG_PSEUDO_DEFAULT));
// Set seed
CHECK_CURAND_CALL(curandSetPseudoRandomGeneratorSeed(gen, 1234ULL));
// Generate n floats on device
thrust::device_vector<float> vec_rnd_d(n);
float* ptr_rnd_d = thrust::raw_pointer_cast(vec_rnd_d.data());
CHECK_CURAND_CALL(curandGenerateUniform(gen, ptr_rnd_d, n));
thrust::device_vector<float> vec_low_d(n);
thrust::device_vector<float> vec_high_d(n);
for (int i = 0; i < 5; ++i) {
EventTimer timer;
timer.start();
thrust::device_vector<float>::iterator iter_end;
iter_end = thrust::copy_if(vec_rnd_d.begin(), vec_rnd_d.end(), vec_low_d.begin(), is_low());
thrust::copy_if(vec_rnd_d.begin(), vec_rnd_d.end(), vec_high_d.begin(), is_high());
timer.stop();
std::cout << "copy_if: " << timer.elapsed() << "ms" << std::endl;
// check result
thrust::host_vector<float> vec_rnd_h = vec_rnd_d;
thrust::host_vector<float> vec_low_h = vec_low_d;
thrust::host_vector<float> vec_high_h = vec_high_d;
thrust::host_vector<float>::iterator low_iter_h = vec_low_h.begin();
thrust::host_vector<float>::iterator high_iter_h = vec_high_h.begin();
for (thrust::host_vector<float>::iterator rnd_iter_h = vec_rnd_h.begin();
rnd_iter_h != vec_rnd_h.end(); ++rnd_iter_h) {
if (*rnd_iter_h <= SPLIT) {
assert(*low_iter_h == *rnd_iter_h);
++low_iter_h;
}
else {
assert(*high_iter_h == *rnd_iter_h);
++high_iter_h;
}
}
}
for (int i = 0; i < 5; ++i) {
thrust::device_vector<float> vec_rnd_copy = vec_rnd_d;
EventTimer timer;
timer.start();
thrust::device_vector<float>::iterator iter_split =
thrust::stable_partition(vec_rnd_copy.begin(), vec_rnd_copy.end(), is_low());
timer.stop();
size_t n_low = iter_split - vec_rnd_copy.begin();
std::cout << "stable_partition: " << timer.elapsed() << "ms" << std::endl;
// check result
thrust::host_vector<float> vec_rnd_h = vec_rnd_d;
thrust::host_vector<float> vec_partitioned_h = vec_rnd_copy;
thrust::host_vector<float>::iterator low_iter_h = vec_partitioned_h.begin();
thrust::host_vector<float>::iterator high_iter_h = vec_partitioned_h.begin() + n_low;
for (thrust::host_vector<float>::iterator rnd_iter_h = vec_rnd_h.begin();
rnd_iter_h != vec_rnd_h.end(); ++rnd_iter_h) {
if (*rnd_iter_h <= SPLIT) {
assert(*low_iter_h == *rnd_iter_h);
++low_iter_h;
}
else {
assert(*high_iter_h == *rnd_iter_h);
++high_iter_h;
}
}
}
CHECK_CURAND_CALL(curandDestroyGenerator(gen));
return EXIT_SUCCESS;
}
Output:
C:\rd\projects\cpp\test_cuda\Release>test_cuda.exe
copy_if: 40.2919ms
copy_if: 38.0157ms
copy_if: 38.5036ms
copy_if: 37.6751ms
copy_if: 38.1054ms
stable_partition: 59.5473ms
stable_partition: 61.4016ms
stable_partition: 59.1854ms
stable_partition: 61.3195ms
stable_partition: 59.1205ms
To answer my own question, I finally found thrust::stable_partition, which is more efficient and elegant than all "copy_if"-alternatives. It just moves all elements that fail to satisfy a predicate to the end of the array and returns the start of the second sequence. Pointer arithmetic gives the size of B, but in fact it's not necessary anymore:
thrust::device_vector<float>::iterator iter = thrust::stable_partition(A.begin(), A.end(), pred)
thrust::device_vector<float> B(iter, A.end())
A.erase(iter, A.end());

C++ program called "Palindrome integer" two func. Function 1// Return reversal integer. Function 2// Returns true if palindrome

Please Help
I am writing a program in C++ using visual basic 2010 the program is called "Palindrome integer" I need to write two functions one that//Return the reversal of an integer. For example reverse(456) returns 654
//with header:-->
int reverse(int number)
I need to write another function that//Returns true if number is a palindrome
//with header:-->
bool isPalindrome(int number)
I need to use the reverse function to implement the function isPalindrome. A number is a palindrome if the numbers reversal is the same as itself. My program should report whether the number is a palindrome. Everything is in one file.
I think this program worked when I first wrote the code not as two functions but just directly into int main(). But I must put the code into the specified two functions and once I had done that and made the adjustments I got the following error messages and the black cout display box didn't appear. Here's a snippet of the error report followed by the full error report
: error LNK2005: "int __cdecl reverse(int)" (?reverse##YAHH#Z) already defined in Driver.obj
:fatal error LNK1169: one or more multiply defined symbols found
I'm getting the following Error Report
1>------ Build started: Project: Palindrome integer, Configuration: Debug Win32 ------
1>Build started 12/7/2013 4:54:25 PM.
1>InitializeBuildStatus:
1> Touching "Debug\Palindrome integer.unsuccessfulbuild".
1>ClCompile:
1> All outputs are up-to-date.
1>ManifestResourceCompile:
1> All outputs are up-to-date.
1>implementation.obj : error LNK2005: "int __cdecl reverse(int)" (?reverse##YAHH#Z) already defined in Driver.obj
1>c:\documents and settings\dell\my documents\visual studio 2010\Projects\Palindrome integer\Debug\Palindrome integer.exe : fatal error LNK1169: one or more multiply defined symbols found
1>
1>Build FAILED.
1>
1>Time Elapsed 00:00:02.25
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
//Bellow is my Code
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
//Retun reversal of an integer
int reverse(int number); //function prototype
//Return true if number is a palindrome
bool isPalindrome(int number); //function prototype
//Driver
int main()
{
int usersNumber = 456; //0; //a few lines commented tempararily for easier number testing
// cout<<"Enter a number and I'll tell you if it's a Palindrome: ";
// cin>> usersNumber;
bool palindromeToF = (isPalindrome(usersNumber));
if (palindromeToF == true)
{
cout <<"YES the number is a Palindrome";
}
else
{
cout <<"NO the number is not a Palindrome";
}
return 0;
}
//function Implementation
//Retun reversal of an integer
int reverse(int number)
{
//do while loop to count number of digits in Number
int digitsCount = 0;
double exponent1 = 1.0;
int quotient;
do
{
int tenToPower = pow( 10.0, exponent1);
// cout <<"tenToPower "<< tenToPower <<"\t ";
quotient = (number / tenToPower);
// cout <<"exponent1 "<< exponent1<<"\t ";
exponent1++;
//cout <<"quotient "<< quotient<< "\t "<<endl;
digitsCount++;
}while (!quotient == 0);
//populating array "arrDigits" with integer's digits
int *arrDigits = NULL;
arrDigits = new int[digitsCount];
double exponent2 = 0.0;
for(int i = 0; i < digitsCount; i++)
{
int powerOfTen = pow( 10.0, exponent2);
//cout <<endl<<"adding "<<((number / powerOfTen) % 10) <<" to sum";
//cout <<powerOfTen;
arrDigits[i]= ((number / powerOfTen) % 10);
exponent2++;
}
//reverse number & populate array "arrDigRevers" with reversed order number
int *arrDigRevers = NULL;
arrDigRevers = new int[digitsCount];
int j = 0;
int reversedNum = 0;
double exponent3 = 0.0;
for(int i = digitsCount-1; i >= 0; i--)
{
int powerOfTenB = pow( 10.0, exponent3);
reversedNum += (powerOfTenB * arrDigits[i]); //return of reverse func.
exponent3++;
/* //reversed integer put into array
if(j < digitsCount)
{
arrDigRevers[j] = arrDigits[i];
//cout <<"\t"<< "arrDigRevers"<<"["<< j<<"]="<< arrDigRevers[j]<<" "<< "arrDigits"<<"["<< j<<"]="<< " "<<arrDigits[j]<<" ";
j++;
}
*/
}
delete[] arrDigits;
delete[] arrDigRevers;
arrDigits = NULL;
arrDigRevers = NULL;
//cout <<endl<<"reversed number is "<< reversedNum;
return reversedNum;
}
//function Implementation
//Return true if number is a palindrome
bool isPalindrome(int number)
{
if(number == reverse(number))
{
return true;
}
else
{
return false;
}
}
The answer lies here:
1>implementation.obj : error LNK2005: "int __cdecl reverse(int)" (?reverse##YAHH#Z) already defined in Driver.obj
It appears that have defined int reverse(int number) in both implementation.cpp and Driver.cpp. You need to rename or remove one of these definitions from your project.

Strcmp not with working data in mysql

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <mysql.h>
#include <my_global.h>
void replace(char * o_string, char * s_string, char * r_string) {
char buffer[1024];
char * ch;
if(!(ch = strstr(o_string, s_string)))
return;
strncpy(buffer, o_string, ch-o_string);
buffer[ch-o_string] = 0;
sprintf(buffer+(ch - o_string), "%s%s", r_string, ch + strlen(s_string));
o_string[0] = 0;
strcpy(o_string, buffer);
return replace(o_string, s_string, r_string);
}
int main()
{
MYSQL *pConn;
MYSQL_RES *pRes;
MYSQL_ROW aRow;
MYSQL_FIELD *field;
int nfields, iCounter;
pConn = mysql_init(NULL);
char aPassword[1024]="";
if (pConn == NULL){
printf("Error %u: %s\n", mysql_errno(pConn), mysql_error(pConn));
exit(1);
}
if(mysql_real_connect(pConn, 0, "root",aPassword,"data",0,NULL,0) == NULL){
printf("Error %u: %s\n", mysql_errno(pConn), mysql_error(pConn));
exit(1);
}
char *info;
printf("Content-type:text/html\n\n");
printf("<html><body>");
info = getenv("QUERY_STRING");
char sub[20]="";
int nsub;
char teacher[20]="";
char room[20]="";
int nroom;
int count=0;
char *token;
char arr[5][20];
char data[1024];
char aCommand[1024];
char data2[1024];
replace(info,"%20"," ");
replace(info,"name=","");
token = strtok(info, " ");
while(token!=NULL){
strcpy(arr[count],token);
count++;
token = strtok(NULL," ");
}
if(count==5){
strcat(arr[0]," ");
strcat(arr[0],arr[1]);
strcpy(sub,arr[0]);
strcpy(teacher,arr[2]);
strcat(arr[3]," ");
strcat(arr[3],arr[4]);
strcpy(room,arr[3]);
}
if(count==4){
strcat(arr[0]," ");
strcat(arr[0],arr[1]);
strcpy(sub,arr[0]);
strcpy(teacher,arr[2]);
strcpy(room,arr[3]);
}
strcat(teacher," ");
strcat(teacher,room);
strcat(sub," ");
strcat(sub,teacher);
puts(sub);
sprintf(aCommand,"select * from Schedule");
mysql_query(pConn, aCommand);
pRes = mysql_store_result(pConn);
nfields = mysql_num_fields(pRes);
while ((aRow = mysql_fetch_row(pRes))){
if(strncmp(aRow[2],sub,strlen(sub)-1)==0)
puts("YS");
else
puts("NO");
}
mysql_free_result(pRes);
mysql_close(pConn);
printf("</body></html>");
return 0;
}
That's the whole code. I don't know where the problem is. After I parsed the query string and display them, it seems that the field and the parsed string are equal. But I've been trying to use strcmp and they just won't work. What could be the error?
I found the problem. I tried using strstr to find the string that only matches with the data in the MySQL table. It doesn't match the whole string so I just modified the program. Instead of matching the whole string, I just used a part of the string to match with the data in the table.