samedi 25 avril 2015

Operator << overload for ofstream


I would appreciate if you could take a look and tell me what im doing wrong. I want to overload an operator for writing object values into a file. Here is what i came up with.

template<typename T>ofstream &operator<<(ofstream &f, const config<T> &X)  
{
    if(X.attribName1.size()!=0)
    {f<<X.attribName1;
for(int i=0;i<3;i++)
        {

            f<<X.attribute1[i];
}}

return f;

}

Implementation :

FILE1NAME="Config_file_no1";
ofstream file1(FILE1NAME+".ini");
    ofstream file2;

    config<double> first;
    first.setAttribName1(file1name1);
    first.setAtt1(val2);


    file1<<first;

The file gets created but its empty. Anyone has any suggestions ? Im thankful for any help.


What is the fastest way to check an internet connection using C or C++?


I'm trying to write a program in C/C++ to check the internet connection on a windows machine. Any help is appreciated. Thank you.


Segmentation fault while using array of char arrays


i have C program. It compiles and works fine, without errors, gives proper results, but when i run debugger, i get segmentation fault. I'm advised to solve this issue, but i don't know whats wrong.

This causes problems:

char names[20][20]; //is this correct?

for(i=0;i<20;i++)
{
    strcpy(names[i],base[i].name);
}

for(i=19;i>=0;i--)
{
    for(j=0;j<i;j++)
    {
        if(strcmp(names[j],names[j+1])>0)
        {
            strcpy(temp,names[j]);
            strcpy(names[j],names[j+1]);
            strcpy(names[j+1],temp);
        }
    }
}

Those elements in base[i].name are:

char name[20];

base = (person*) malloc(20 * sizeof(person));

Generally speaking, all of involved structures have length 20, so I don't know what I'm doing wrong. I guess I'm trying to access memory which I shouldn't, but where?


How to pack the C code with NDK and run it on Android phone?


My team and I are working on a project by coding in C. We finished coding part, and then we need to bring the project into Android phone.

I installed Android SDK, NDK, eclipse. I try to run our C project in eclipse and it works.

So for the next step, what should we do? How to pack the code by using NDK and test it??

Thank you so much


JPEG source-code and quantization mode change - C language


I'm assigned to do a project that consists in changing the quantization in the JPEG source-code, from the quantization tables to Lloyd-Max quantization. The problem is not knowing what to do (I know how to change the quantization), but where to find the code I'm suposed to change. If someone is familiar with the libjpeg-turbo, could you give me some advice on doing so?


fast way to get integers 0, 1, and 2 when given a random one from the set


So basically

int num = rand(2); //random number from 0-2
int otherNum, otherOtherNum;
otherNum = implement this
otherOtherNum = implement this

For example, if num is 2, otherNum and otherOtherNum must be set to 0 and 1 (or 1 and 0).

How would you implement this? What's a fast way? Assume you can't use branching or look up tables.


Creating multiple threads in C: write pid, tid and return integer


I must do this:

Write a program whose main thread creates 3 other threads. Each ot these threads (different from the main thread) shall write its pid and tid and terminate returning an integer number between 1 and 3 and different from the value returned by the other threads. The main thread shall print in the standard out its pid and the value returned by each of the other threads.

I think I'm doing it right, except that I don't understand how should I return the integer numbers between 1 and 3

I've the following code so far:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#define DEBUG 0

// int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void*), void *arg);

// int pthread_join(pthread_t, void **value_ptr);

void *printID(void *arg){

    int i;

    unsigned long tid;
    tid = *((unsigned long *) arg);           

    printf("Thread tid: %lu Thread pid: %d \n", tid, getpid());

}

int main(int argc, char *argv[]) {

    pthread_t id1, id2, id3;

    pthread_create(&id1, NULL, printID, &id1);

    pthread_create(&id2, NULL, printID, &id2);

    pthread_create(&id3, NULL, printID, &id3);

    pthread_join(id1, NULL);

    pthread_join(id2, NULL);

    pthread_join(id3, NULL);

    printf("Main thread pid: %d\n", getpid());

    sleep(1);

}


Random function changing randomly [on hold]


m looking for a random function to generate random numbers which (internally) changes randomly and should be unpredictable by the hackers....can anyone please provide me with some suggestions?...you all could also suggest me to develop my own function.

And how should I develop a relation between two random functions changing randomly? (if I use same function at two different places)...I hope that I am clear enough


Trouble with Bailey-Borwein-Plouffe formula


I am trying to implement the BBP formula. I wrote the following quick and dirty test code, based on the paper by Paul H. Bailey (that I found here):

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gmp.h>
#include <limits.h>

long bin_exp_mod_k(int base, int exponent, int div) {
    long expmod = 1;
    long t;

    t = (long) pow(2, floor(log(exponent)/log(2.0)));

    while(42) {
        if(exponent >= t) {
            expmod = (base * expmod) % div;
            exponent -= t;
        }

        t = t/2;

        if(t >= 1) {
            expmod = ((long)pow(expmod, 2)) % div;
        } else
            break;
    }

    return expmod;
}

void bbp_part(mpf_t rop, int base, int index, int digit_index, int num_iter) {
    const int knum = num_iter;
    int k;
    long ldiv;
    mpf_t fbase;
    mpf_t fst_sum;
    mpf_t fst_sum_int;
    mpf_t snd_sum;
    mpf_t powval;
    mpf_t div;

    mpf_init(fst_sum);
    mpf_init(snd_sum);
    mpf_init(fst_sum_int);
    mpf_init(powval);
    mpf_init(div);
    mpf_init(rop);
    mpf_init_set_si(fbase, base);

    for(k = 0;k <= digit_index;k++) {
        ldiv = 8 * k + index;
        mpf_set_si(powval, bin_exp_mod_k(base, digit_index - k, ldiv));
        mpf_set_si(div, ldiv);
        mpf_div(powval, powval, div);
        mpf_add(fst_sum, fst_sum, powval);
    }

    mpf_trunc(fst_sum_int, fst_sum);
    mpf_sub(fst_sum, fst_sum, fst_sum_int);

    for(k = digit_index + 1;k < knum;k++) {
        ldiv = 8 * k + index;
        mpf_set_si(div, ldiv);
        mpf_pow_ui(powval, fbase, digit_index - k);
        mpf_div(powval, powval, div);
        mpf_add(snd_sum, snd_sum, powval);
    }

    mpf_set(rop, fst_sum);
    mpf_add(fst_sum, fst_sum, snd_sum);

    printf("S%i: %.20lf\n", index, mpf_get_d(rop));

    mpf_clear(fst_sum);
    mpf_clear(snd_sum);
    mpf_clear(fbase);
    mpf_clear(fst_sum_int);
    mpf_clear(powval);
    mpf_clear(div);
}

int main(int argc, char **argv) {
    const int base = 16;
    int d;
    int num_iter;
    mpf_t pi_digits;
    mpf_t part1;
    mpf_t part1_int;
    mpf_t part4;
    mpf_t part4_int;
    mpf_t part5;
    mpf_t part5_int;
    mpf_t part6;
    mpf_t part6_int;

    if(argc == 1) {
        return -1;
    }

    d = atoi(argv[1]);

    if(argc == 3) {
        num_iter = atoi(argv[2]);
    } else {
        num_iter = INT_MAX;
    }

    mpf_set_default_prec(128);

    mpf_init(pi_digits);

    mpf_init(part1_int);       
    mpf_init(part4_int);
    mpf_init(part5_int);
    mpf_init(part6_int);

    bbp_part(part1, base, 1, d, num_iter);
    bbp_part(part4, base, 4, d, num_iter);
    bbp_part(part5, base, 5, d, num_iter);
    bbp_part(part6, base, 6, d, num_iter);

    mpf_trunc(part1_int, part1);
    mpf_trunc(part4_int, part4);
    mpf_trunc(part5_int, part5);
    mpf_trunc(part6_int, part6);

    mpf_sub(part1, part1, part1_int);
    mpf_sub(part4, part4, part4_int);
    mpf_sub(part5, part5, part5_int);
    mpf_sub(part6, part6, part6_int);

    mpf_mul_ui(part1, part1, 4L);
    mpf_mul_ui(part4, part4, 2L);

    mpf_set(pi_digits, part1);
    mpf_sub(pi_digits, pi_digits, part4);
    mpf_sub(pi_digits, pi_digits, part5);
    mpf_sub(pi_digits, pi_digits, part6);

    mpf_clear(pi_digits);
    mpf_clear(part1);
    mpf_clear(part4);
    mpf_clear(part5);
    mpf_clear(part6);
    mpf_clear(part1_int);
    mpf_clear(part4_int);
    mpf_clear(part5_int);
    mpf_clear(part6_int);

    return 0;
}

and it seems to be correct, because according to his paper the partial results I get for S1, S4, S5 and S6 are, with a small precision difference, the same ones noted.

However, I can't figure out what I did miss with the "combining the results" part. No matter what I do, I get 0.57... instead of the 0.42... written on the paper.

Can someone see what am I missing here?


incrementing values in if loop (in C)


I am writing a self-controlled Pacman game (Pacman moves by itself by algorithms which decide it's movement, needs to chase ghosts, etc.) in C. Keep in mind that I am very new to programming in C so the method I use may not be a good one at all.

Anyways, I stumbled upon a problem.

my Pacman moves in an Array map with it's placement at

Map[yPacman][xPacman] == place of Pacman;

Now, when Pacman is in "rage mode"; after picking up a sweet, I would like him to find the ghosts he seeks. The ghost being a char 'G' in the array.

Now, I would like Pacman to see ahead of him to catch and follow the ghost when it reaches a distance near him. Let's say he's moving to the left; I would him to look 5 "X-Coords" left of him, including the X-coords "1,2,3,4,5". When any of these coordinates equal to a char 'G', it'd have to follow him.

Now, I would like to implement it, but I can't seem to find a way how to.

if (Map[yPacman][xPacman-i] == 'G')  { }

With "i" having a value from 1-5. Incrementing it during the process itself. I would not like to use

if (Map[yPacman][xPacman-1] == 'G' || Map[yPacman][xPacman-2] == 'G'|| Map[yPacman][xPacman-3] == 'G'|| Map[yPacman][xPacman-4] == 'G'|| Map[yPacman][xPacman-5] == 'G')  { }

Even though this is the exact result I would need.

I personally think it seems very easy to solve how to do this. But at the moment I have no clue. Thanks in advance


Pointer for pointer


I try to insert new node to tree without using recursive function.

Root is global defined first node of tree.

node *tree;
tree=&root;

.......

(tree->tab[first])=(node*)malloc(sizeof(node));

Where node is my own defined structure. I want to have handle to root, so I make new pointer, which I will use to move on tree. I m very suprised because new allocated nodes arent assigned to my root. How can I do that? How can edit root by editing tree.

Please help, I have spent hours for that problem. Greetings


matrix represents tree the function returns 0


I have some homwrok and it looks like this: Question 1 ( First program adjacency.c file ) Directed tree structure T has N nodes represented by the adjacency matrix A size NxN as follows:

A [ u ] [ v] == TRUE if and only if there is a directed arc from u to v in T , or in other words : u is the parent of v . In the following example a tree with N = 11 nodes :

tree

We obtain the following neighboring matrix :

matrix

this are the questions:

A. You must define with #define command and / or enum the N and permanent TRUE and FALSE. Typedef should be set with a character named adj_mat defines the neighboring matrix size N.

B. You must write a function called path, which accepts as a parameter adjacency matrix A and indexes of two nodes u and v and returns TRUE if and only if there is a directed path (by directional arrow) at the intersection u v, the tree is represented by a matrix A. Otherwise it returns FALSE.

For example: path (1,8) will return TRUE. The same path (1,3). On the other hand path (3,8) will FALSE.

C. First you must write a function (main) defines a variable type adj_mat, asks the user entries for this matrix, and indexes of the two nodes. The main function function call path, to see if there is a directed path between two nodes in the data. The function to print the test result output.

have to get some help guys

#include <stdio.h>

#define N 11
enum {FALSE, TRUE};
typedef int adj_mat[N][N];

int path2(adj_mat A, int u, int v, int temp)
{
if(u == temp && A[u][v] == FALSE)
return TRUE;

if(u == temp && A[u][v] == FALSE)
return FALSE;

if(A[u][v] == FALSE)
return path2(A, u-1, v, temp);

if(A[u][v] == TRUE)
return path2(A, N, u, temp);

return FALSE;
}

int path(adj_mat A, int u, int v)
{
return path2(A, N, v, u);
}



int main()
{

int arr[N][N]= {{0,1,1,1,0,0,0,0,0,0,0},{0,0,0,0,1,1,1,1,1,0,0},
{0,0,0,0,0,0,0,0,0,1,0},{0,0,0,0,0,0,0,0,0,0,1},{0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,0,0}};
int u;
int v;
printf("please enter two numbers \n");
scanf("%d %d", &u, &v);
printf("The answer is %d", path(arr, u, v),".");
return 0;
}

The problem is at the terminal when i put 1,8 it returns 0. please help me guys im going inasane


error in sending char array using c socket programming


Below is a code for transferring char array from client to server but server is not able to receive array and display the content of the received array also there is a warning as follows:

assignment makes integer from pointer without a cast [enabled by default]
     temp_char_arr[i]=recvs_bytes[i];

please help me solve this problem

thanks in advance.

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include<signal.h>

#define PORT 2021

int sd,ad,pid,len = 0,i;
float p;
char buf[100];
char* recvs_bytes[11],temp_char_arr[11];


void save_bytes(const char *filename,char* temp_char_arr[]);

void Die(char *mess)
{
    perror(mess); exit(1); 
}
int main()
{

    printf("\nEnter server port:2020 and server          ip:192.168.204.138\n");        
    struct sockaddr_in serverAddress;
    if((sd = socket(AF_INET,SOCK_STREAM,0)) < 0)
    {
        Die("Error creating socket");
    }
    memset(&serverAddress, 0, sizeof(serverAddress));
    serverAddress.sin_family = AF_INET;
    serverAddress.sin_port = htons(PORT);
    serverAddress.sin_addr.s_addr = htonl(INADDR_ANY);

    if(bind(sd, (struct sockaddr*)&serverAddress, sizeof(serverAddress)) < 0)
    {
        Die("Bind error");
    }

    if(listen(sd, 5) < 0)
    {
        Die("Listen error");
    }
    printf("\n***************************serveronline*****************************\n");
    while(1)
    {
        ad = accept(sd, (struct sockaddr*)&serverAddress, &len);
        pid=fork();
        if(pid<0) 
            Die("Fork error");

        if(pid==0)
        {
            p=1.0;
            if(send(ad,&p,sizeof(float),0)< 0)  Die("Error sending data");
            printf("\nreceivieng bytes\n");
            if(recv(ad, recvs_bytes, sizeof(recvs_bytes), 0) <0) Die("Receive error");
            for(i=0;i<=10;i++)
            {
                temp_char_arr[i]=recvs_bytes[i];
                printf("%s",&temp_char_arr[i]);
            }
            printf("\nbytes received\n");
            close(sd);
            exit(0);
        }
        if(pid>0)
        {
            close(ad);
        }
    }

    return 0;
}

client.c

#include <stdio.h>
#include <sys/statfs.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <signal.h>
#include <netinet/in.h>
#include <string.h>
#include <stdlib.h>
#include<signal.h>


char *trans_bytes[11],arr[11];
FILE *ptr_file;
char* temp[11],arr[11];
int sd,i;
float q;

void func();
void send_trans_bytes(char* arr[]);

void Die(char *mess) { perror(mess); exit(1); }

int main(int argc, char *argv[])
{
    if (argc != 3) {
        printf("USAGE: TCPecho <server_ip> <port>\n");
        exit(1);
    }

    struct sockaddr_in clientAddress;
    if((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        Die("Error creating socketsss");
    }

    memset((char *)&clientAddress, 0, sizeof(clientAddress));

    clientAddress.sin_family = AF_INET;
    clientAddress.sin_addr.s_addr= inet_addr(argv[1]);
    clientAddress.sin_port = htons(atoi(argv[2]));
    if ((connect(sd,(struct sockaddr *)&clientAddress, sizeof(clientAddress))) < 0)
    {
        Die("Error connectiong to server!");
    }
    printf("\n--------------------client online----------------------------\n");

    if(recv(sd, &q, sizeof(float), 0) < 0)  {    Die("Receive error");   }
    if (q==1.0)
        printf("\nsignal receivied=%f\n",q);
    func();
    return 0;
}


void func()
{
    int i;
    for(i=0;i<=10;i++)
        temp[i]="some_text";
    send_trans_bytes(temp);
}


void send_trans_bytes(char* arr[])
{
    if(send(sd,arr, sizeof(arr), 0) < 0) Die("Error sending host name");
    for(i=0;i<=10;i++)
        printf("arr[%d]=%s",i,arr[i]);
}


C: Reading multiple areas into an array and finding the largest value


I'm attempting to find the largest value in an array. I'm given a set of areas (the input), which for now is:

4.5
19.59
1.92

These areas need to be read into an array using scanf and then from there I need to find the largest value (area) in that array. It should also be known that there can only be maximum of 100 areas that can be read into the array. So later on I may need to read in 5 or 20 or 99 etc... into the array.

If anybody could give me a hand it'd be much appreciated, I'm new to programming and don't really know where to begin.


Where is the implementation of dm_task_create in cryptsetup?


Where is the implementation of the function dm_task_create in cryptsetup (and other dm_task_ related functions)? Grepping for this function in the source for cryptsetup I come up with nothing. I see it is used in lib/libdevmapper.c and that it has a function prototype in libdevmapper.h. However where is the implementation? As a side note, cryptsetup compiles fine and executes.

Just to check, I grepped through the kernel source as well but it doesn't appear to be implemented in the kernel either.

From the following link http://ift.tt/1IWARep it appears that at least in the past it was implemented in libdevmapper.c.


Hello world obfuscated


I encountered the following code

#include <stdio.h>

int main(void)
{
    long long P = 1,E = 2,T = 5,A = 61,L = 251,N = 3659,R = 271173410,G = 1479296389,
              x[] = { G * R * E * E * T , P * L * A * N * E * T };
    puts((char*)x);
    return 0;
}

The case is I do not quite understand how it works,It is very confusing to me. Can someone you please explain this in detail?

edit:

One more thing, how to make print hello world in Spanish


Matrix column mirror like rearrange in C#


First of all, thanks for taking the time to look at my post. I'm new to C# and programming in general, so i need a little help with some homework. I have to first insert the number of rows and columns, then the elements and show the whole matrix. After that to arrange the columns in a mirror like way. For example: If the matrix has one row and 5 columns, it should look like this:

Matrix 1 2 3 4 5 should become 5 4 3 2 1

The same thing goes for more than one row.

This is what i did so far:

#include <stdio.h>

void main()
{
int m, n, i, j, matrix[10][10];
printf("Insert the number of rows and columns:\n");
scanf("%d%d", &m, &n);
printf("Insert the desired elements:\n");
for (i = 1; i <= m; i++)
for (j = 1; j <= n; j++)
scanf("%d", &matrix[i][j]);
printf("Your matrix has the following elements:\n");
for (i = 1; i <= m; i++)
{
for (j = 1 ; j <= n; j++)
{
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
}

If there is a better way, or i did something wrong please tell me. As i said i'm new to programming. Thanks in advance.


counting the number of times a character appears in a file in a case insensitive manner using C language


The problem statement : a C program to count the number of times a character appears in the File. character is considered Case insensitive. I have converted both the input character and character from the file to upper case so that none of the occurrence of the character goes uncounted. but when am executing this on an online editor am getting the result as "wrong answer" the editor isn`t accepting this code. what is the mistake in this code??

    #include<stdio.h>
    #include<ctype.h>
    #include<stdlib.h>
    int main
    {
     FILE *fp;
     char filename[20];
     char character;
     char compare;
     int to_upper1;
     int to_upper2;
     int count=0;
     printf("\nEnter the file name");
     scanf("%s", filename);
     fp = fopen(filename,"r");
     if(fp == NULL)
     {
       exit(-1);
     }
     printf("\nEnter the character to be counted");
     scanf("%c", &character);
     to_upper1 = toupper(character);
     while((compare = fgets(fp)) != EOF)
     {
       to_upper2 = toupper(compare);
       if(to_upper1 == to_upper2)
          count++;
     }
     printf("\nFile \'%s\' has %d instances of letter \'%c\'", filename, count,      character);
return 0;
}


'Grokkable' algorithm to understand exponentiation where the exponent is floating point


To clarify first:

  • 2^3 = 8. That's equivalent to 2*2*2. Easy.
  • 2^4 = 16. That's equivalent to 2*2*2*2. Also easy.
  • 2^3.5 = 11.313708... Er, that's not so easy to grok.

Want I want is a simple algorithm which most clearly shows how 2^3.5 = 11.313708. It should preferably not use any functions apart from the basic addition, subtract, multiply, or divide operators.

The code certainly doesn't have to be fast, nor does it necessarily need to be short (though that would help). Don't worry, it can be approximate to a given user-specified accuracy (which should also be part of the algorithm). I'm hoping there will be a binary chop/search type thing going on, as that's pretty simple to grok.

So far I've found this, but the top answer is far from simple to understand on a conceptual level.

The more answers the merrier, so I can try to understand different ways of attacking the problem.

My language preference for the answer would be C#/C/C++/Java, or pseudocode for all I care.


A C code to reverse a string


Does anybody see the bug here? I have got alternate solutions.

int main()
{

  char line[100], res[100], temp[20];
  fgets( line, 100*sizeof(char), stdin);    
  int i, j, l;
  for( i=strlen(line)-1; i>=0; i--)
  {
    if(line[i]==' ')
        for(j=i+1, l=0; line[j]!=' ' && line[j]!='\0'; l++, j++)
            temp[l]=line[j];
    temp[++l]=' ';
    temp[++l]='\0';
    strcat(res, temp);
  }
  puts(res);
  return 0;
}


How to reuse a literal in a char and a one-character string variable?


I need to specify an argument short option (e.g. -f) both as char and char[] in c code. In order to maximize code reusage I want to declare a variable which allows me to change the value in one place (a "literal" - not stringly speaking a string or char literal, but in the sense of the abstract concept). I would prefer a solution which solves this exclusively in preprocessor constants and functions/macros or exclusively in c code to a good explanation why this has to be solved in a mixture of both.

I tried

  • to #define FOREGROUND_OPTION_VALUE 'F' which causes me trouble to transform it to a char[] (as preprocessor constant) (writing a macro which stringifies with # causes the ' quotes to be stringified as well
  • to omit the ' quotes which leaves me with the problem of creating the ' quotes or create a char another way.

Is there any way to perform something alike std::bind in C?


So I have a function of type void (*actionOnM)( void * myTypeInstance) and I need to wrap it into and pass as void (*action)(). Is such thing possible in C?


Log file using RPC in c


The Question is write a RPC client and Server code on Linux such that from any point of time using server you can get log file till that time of a particulate file which sits on client .

please help me out Can't find way to start


array to create a linked-list


typedef struct num{
    int num;
    int pre;
    struct num* next;
}Num;

Num list[10]=
{{3,4},{2,1},{6,5},{7,2},{4,3},{3,9},{5,6},{1,3},{8,4},{10,0}
};

#include <stdio.h>

int main(){

    int cnt;
    Num *ptr = NULL;

    Num tempTwo;
    for (cnt = 0; cnt < 10; cnt++) {
        tempTwo = list[cnt]; 
        ptr->next = &tempTwo; //Error
        ptr = ptr->next;
    }

    for (cnt = 0; cnt<10; cnt++) {
        printf("num: %d, pre: %d\n",ptr->num,ptr->pre);
        ptr = ptr->next;
    }
}

I want to make linked-list with array 'list' using pointer ptr.
Error: Bad access
What can I do to solve this problem?


Should the static and inline functions be defined in .h file?


When I write software in C, should I put static and inline functions in the .h or in the .c file?


OpenGL lighting vector normalization


I am attempting to find the vector normalization for an arbitrary object loaded into an opengl program. I am trying to calculate the normals for all the vertices (assuming this is what I need to do) for the lights. When I run the program some of the object is lit correctly, but for the most part it is not. The majority of the faces are lit separately with some of them not lit at all.

Here is the code I am using for trying to calculate the normals of each vertex.

vec3 one, two;
for(int i = 0; i < object.vertexNumber; i++)
{
    one.x = normals[i+1].x - normals[i].x;
    one.y = normals[i+1].y - normals[i].y;
    one.z = normals[i+1].z - normals[i].z;

    two.x = normals[i+2].x - normals[i].x;
    two.y = normals[i+2].y - normals[i].y;
    two.z = normals[i+2].z - normals[i].z;

    vec3 normal = normalizevec3(crossvec3(one, two));

    normalized[i] = normal;
}

and the function I am using to normalize the vectors

vec3 normalizevec3(vec3 v) {
float vecLength = lengthvec3(v);
vec3 dividebyzero = {0.0, 0.0, 0.0};
if (vecLength == 0)
    return dividebyzero;
float X, Y, Z;
X = v.x / vecLength;
Y = v.y / vecLength;
Z = v.z / vecLength;
vec3 u = {X, Y, Z};
return u;
}


How to write a simple "page fault generator"?


For my course project on Linux Kernel, I need to simulate a situation where there is a lot of page swapping due to low memory.

I want to write a program which needs a lot of physical memory, so that pages accessed by this program have to be swapped in and out multiple times.


can't get string conversion strtod in c (fixed)


Could somebody help me(sorry for the english), Im trying to convert a string to a double but when I can't get it here's my code(thank you, I'll appreciate help so much):

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAX_LONG 5

char bx[MAX_LONG];
double cali=0;

int main() {                              /*(here */
scanf("%s",bx); /*here was the error scanf("%c",bx)*/
cali = strtod(bx,NULL);
printf("%f",cali);
return 0;
}

when I input a value greater than 10 in the output it just print the first number like this:

 input: 23
 output: 2.00000
 input: 564
 output: 5.00000


Cannot place kernel's prototype in header


io.cuh:

#ifndef IO_CUH
#define IO_CUH

#include <cuda.h>

typedef struct{
    unsigned width;
    unsigned height;
    unsigned char *image; //RGBA
}rgb_image;

__global__ void transformToGrayKernel(rgb_image *img);
void decodeTwoSteps(const char* filename, rgb_image *img);
void encodeOneStep(const char* filename, rgb_image *img);
void processImage(const char *filename, rgb_image *img);

#endif // IO_CUH

I'm trying to compile simple program using the following makefile:

lodepng.o: lodepng.h
        cc -c lodepng.c -o lodepng.o
io.o: io.cuh lodepng.o
        nvcc -c io.cu -o io.o
main: io.o
        nvcc main.c io.o -o main

'main.c' uses one function from io.cu, which is dependent on lodepng.c.

After some minor warnings that reference to the code, I got the following error:

nvcc main.c io.o -o main nvcc warning : The 'compute_10' and 'sm_10' architectures are deprecated, and may be removed in a future release. In file included from main.c:1:0: io.cuh:12:12: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘attribute’ before ‘void’ global void transformToGrayKernel(rgb_image *img); ^ makefile:6: recipe for target 'main' failed make: *** [main] Error 1


A 'for' loop with ";" at the end


I found the following code:

int func_prim (int zahl) {
  int count;
  if (zahl < 0)
    return -1;

  for (count = 2; zahl % count != 0 && zahl >= count; count++);
  if (count == zahl)
    return 1;
  return 0;
}

The point of function is to check whether a number is a prime number or not.

I don't understand why the for-loop has ; at the end:

                                                            v
for (count = 2; zahl % count != 0 && zahl >= count; count++);

Without that, the code doesn't work properly.

What is the explanation?


How I can fix this array


Good morning, I was trying to fill a dynamic vector but when I print the input data i get something like this:

input: 1,5,3,4,2
output: 0,1,5,3,4

Could somebody help me I can't fix it I've been trying a lot and can't get it. I'll apreciatte so much (sorry for the english)

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAX_STR 10

int vecto();

char seguir[MAX_STRLEN];
int var;

float* vector; 
char* bv;

int vecto(){
int cont=0,ch;
char v[MAX_STR];
printf ("¿number of elements to order?: ");
scanf("%d",&var);
vector = (float*)malloc(var*sizeof(float));
while((ch = fgetc(stdin)) != EOF && ch != '\n' ){};
printf("input number press f for finish \n");
    do{
    fgets(v,sizeof(v),stdin);
    if((strcmp(v,"f")!=0)){
        cont++;
        vector[cont]=strtod(v,&bv);
    }
    }while(!((cont==var) || (strcmp(v,"f")==0)));
printf("\n");
return 0;
}


Are array memory addresses always in the order of least to greatest?


When I'm making a procedure with pointer arithmetic and !=, such as

template <typename T> void reverse_array ( T * arr, size_t n )
{
    T * end = arr + n; 
    while (arr != end && arr != --end) 
    {
         swap(arr,end);
         ++arr;
    }
}

I always take a lot of caution because if I write my procedure wrong then in a corner case the first pointer might "jump over" the second one. But, if arrays are such that

&arr[0] < &arr[1] < ... < &arr[n]

for any array arr of length n-1, then can't I just do something like

template <typename T> void reverse_array ( T * arr, size_t n )
{
    T * end = arr + n;
    if (arr == end) break;
    --end;
    while (arr < end)
    {
        swap(arr,end);
        ++arr; --end;
    }
}

since it's more readable? Or is there a danger looming? Aren't memory addresses just integral types and thus comparable with < ?


Simple Heartbleed example in C


After reading what The Heartbleed Bug is from the http://heartbleed.com website, I am trying to create a very simple example of it using the memcpy() function in C to fully understand what it is and understand why it is such a big deal. Can this easily be done/shown in C?


What are the different data types in C and how would they be used?


I'm new to programming in C and just programming in general.

My question is: What are the different data types in C, how would they be used, and as a side note, how does typecasting work?

Thanks


Pipeline idea not working due to pointers (C)


I was working on a little program I had to make some time ago, and I wanted to short it up.

This little program was about one thread creating several child who would redirect their standard output/input one to another with pipes in order, except for the last child, who won't redirect it's standard output, like this.

Parent pipe  child1   pipe   child2  pipe   last child
       __             __             __
O-----|__|-----O-----|__|-----O-----|__|-----O -> Stdout

First time I face this code, I made a matrix with a dimension of [n_child][2], and made a pipe from every position of that matrix, so it was very easy to connect every pipe to every child when needed. But now I want to try it only with 2 pipes, and "playing" with inheritance.

Maybe I'm not explaining myself really well, so I think everything would be better understood with my code,so here we go.

piping_function(int number_of_child){

    int i;
    int olddesc[2];
    int newdesc[2]; //Here I create the descriptors of the pipes I'll use
    int *olddir;
    int *newdir;
    if(pipe(olddesc)<0 || pipe(newdesc) < 0){  //I create the pipes
        //Error 
    }
    olddir = olddesc;
    newdir = newdesc; //And attach the directions to the array's direction (we will see later why)
    for(i = 0; i < number_of_child; i++){
        chaddr[i] = fork();
        switch(chaddr[i]){
            case -1:
                //Error trace
            case 0:
                dup2(olddesc[0],0); //Here I redirect the pipe who connect the previous child's pipe to the standard input
                if(i != number_of_child - 1)
                    dup2(newdesc[1],1); //And here, except from the last child, I redirect the standard output to the pipe who will connect to the standard input of the next child
                close(olddesc[0]);
                close(newdesc[1]); //I close the descriptors I don't need
                //Several child operations with standard input-output (end up returning 0/1 after the pipeline is connected, so no child will create any child)
            default:
                if(i == 0)
                    dup2(olddesc[1], 1); //I want the standard output of the principal proccess only on the first pipe
                olddir = newdir; //Here I would want the direction of the "old" pipe to be the direction of the "new" pipe, in order to achieve the pipeline
                if(pipe(newdesc)<0)
                    //Error
                break;
        }//End of switch
    }//End of for
    close(olddesc[0]);close(olddesc[1]);close(newdesc[0]);close(newdesc[1]); //I don't need these descriptors anymore, as they must be redirected to the standard's input/output of the process they need.
}//End of function

Well, there is my code. I think I can see the mistake I'm doing, when I make olddir be newdir, and create the pipe, I'm doing olddir to be also that new pipe right? So here comes my question:

Is there any way to achieve that change? I mean, the thing I want is to equal olddir (who is the address of olddesc, right? so if I change that address olddesc's address will be also changed, right?) to newdir, in order to continue with the pipe I created before to redirect the standard output of the "next" child, but I also want newdir to be a NEW pipe.

I don't really know if I explained myself right, I'm not a native speaker and it's a bit difficult to explain these kind of ideas in other language. Feel free to correct any grammar mistake, I'd appreciate it, and to ask any question about the code, as maybe I'm not giving the point I wanted to.

Thanks.


GCC optimization of iterative functions


I have the following code for Fibonacci both for recursive and iterative versions:

#include <stdio.h>

typedef long long INT;

long long recursive (long long i) {
    if (i == 0) return 0;
    if (i == 1) return 1;
    return recursive (i-1) + recursive (i-2);
}


long long iterative (long long i) {
    INT counter = i-1;
    INT fib1 = 0;
    INT fib2 = 0;

    // first iteration
    fib1 = 0;
    fib2 = 1;

    while (counter > 0) {
        INT temp1 = fib1;
        INT temp2 = fib2;
        fib1 = fib2;
        fib2 = temp1 + temp2;

        counter--;
    }

}

int main (int argc, char **argv) {

    printf("Result: %lli\n", iterative(10));

    return 0;
}

I tried compiling it with GCC -O2 optimization to see if recursion would perform better than iteration, but I noticed an interesting occurrence: when compiled with -O2, the iterative function outputs 0 while if it's compiled without the flag, it outputs the proper number.

gcc -O2 fibonacci.c -o fib && ./fib: Result: 0

gcc fibonacci.c -o fib && ./fib: Result: 55


Mex C profiler Mac


I'm looking for a way to do very simple profiling in a mex program triggered from matlab. I compile from matlab using: mex -O CFLAGS="\$CFLAGS -std=c99" rrt.c and then run my program. Really all I need is a thing to see, which of two functions runs faster. However since it all goes down in about 1/100s time(NULL) is not fast enough.

Is there a simple function in C I could call, or are there any real profiling methods for a mex program in matlab?

I saw this post beeing treated as duplicate, but what I want to know is not a C profiler, but something I can use at best within matlab. I use OSX 10.7.5 and matlab 2014b. Thanks for any hints.


Getting a bus error when calling curl_easy_perform() a second time


I'm pretty new to C and Libcurl so please excuse any shoddy coding practices.

So the issue i'm having, when calling the function curl_easy_perform() a second time a I encounter a bus error [EDIT: Specifically: The program received signal SIGBUS] At first I thought it was the way I was setting certain options with curl_easy_setop() However after many hours/days of debugging (hopefully something trivial (non the less way too long)) I found that the culprit was a self written function. the thing that is baffling me is that is does not interact with libcurl in any way, It's only purpose is to strip my api call down to the Barer token. Anyway hopefully my code will make more sense.

Entire code not included however this compiles with no warnings.

int main(int argc, char *argv[]) 
{
    CURL *curl = curl_easy_init();
    curl_socket_t sockfd;
    curl_off_t nread;
    size_t iolen;
    int res;
    long sockextr;
    const char *request;
    struct curl_slist *chunk = NULL;
    struct curl_slist *headers = NULL;
    printf("Setting params\n");

    if(curl) {
        struct string s;
        init_string(&s);
        /* Set URL */
        curl_easy_setopt(curl, CURLOPT_URL, "http://ift.tt/1Jp08l0");
        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
        curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
        /*Add json header*/
        chunk = curl_slist_append(chunk, "Content-type: application/json");
        res = curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
        /* Use SSL*/
        curl_easy_setopt(curl, CURLOPT_SSLVERSION, 1);
        curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_ALL);
        /* Get AuthToken */
        res = curl_easy_getinfo(curl, CURLINFO_LASTSOCKET, &sockextr);
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L)
        if (CURLE_OK != res)
        {
            printf("Error: %s\n", strerror(res));
            return 1;
        }

        printf("Getting Token...\n");

        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writefunc);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s);
        curl_easy_perform(curl);
        printf("\nGot response:%s\n", s.ptr);
        printf("Setting Auth headers...\n");
        char *authtoken = s.ptr; // If I was to call   curl_easy_perform(curl) here there is no bus error
        char *tokenkey = strip(authtoken); 
        curl_easy_perform(curl); // When called here I get a Bus error
        return 0;
}

char *strip(char *json)
{
   // returns Auth token
   printf("strip has got json:%s\n", &json[0]);
   const char s[2] = "\"";
   char *token;
   int i = 0;

   token = strtok(json, s);
   while(token != NULL)
   {
     printf("%s\n", token);
     token = strtok(NULL, s);
     if (i == 2)
     {
       printf("Got Token!%s\n", token);
       return token;
       break;
     }
     i++;
   }
 }


C structure as data type


I want to be able to do something like this:

typedef struct
{
    char* c_str;

} string;

string s = "hello";

Is it possible to do that in any way?

I know that it is possible to do this:

typedef struct
{
    char* c_str;

} string;

string s = { "hello" };

But I do not like the curly brackets when it is only one member variable


Why should "case statement" be constant?


In JavaScript the following statement is valid.

switch(true) {
    case a > b:
        max = a;
        break;
    case a < b:
        max = b;
        break;
    default:
       max = a;
}

But in C/C++ language, when I write this statement, compiler gives me an error showing case statement must be consist of constant values. Sometimes in particular circumstances writing such switch-case statements would be very useful, but C/C++ will not allow me to do so.

Now I am curious to know what is the point behind this to not allowing variable values to be used in case statements?


WINAPI URLDownloadToFileA Problems


i'have used the microsoft WINAPI syntax from http://ift.tt/1HD4fsT

so there is my code

#include <windows.h>

#pragma comment(lib, "urlmon.lib")

HRESULT URLDownloadToFileW( FALSE, "http://ift.tt/1Gt7qAl", "C:\\psych0bOx.png", 0, NULL);

when i try to compile it with msvs 12.0 i'get these errors:

C:\>cl C:\URLDownloadToFileA.cpp

C:\URLDownloadToFileA.cpp(8) : error C2365: 'URLDownloadToFileA' : redéfinition ; la précédente définition était 'fonction' C:\Program Files\Windows Kits\8.1\include\um\urlmon.h(4780) : voir la déclaration de 'URLDownloadToFileA' C:\URLDownloadToFileA.cpp(8) : error C2078: initialiseurs trop nombreux

C:\>

i dont understand why i get therse errs i'm completely blocked here :x


Number of elements in float array in C


i have array of float in C. the length of this array depends of user input. I need to find out number of elements in this array. Example:

float a[10] = {3.1314, 1.5131, 9.133,  10.333}

How can i check number of elements? sizeof(a)/sizeof(a[0]) always give the max number of elements (10 in this case).


Error using mex in Matlab: An illegal memory access was encountered


My system is is Tesla K80,cuda toolkit 7.0 CentOS. I wanted to implement other's codes on my system. First, I concatenate all the c and cu files into test.cu, then compile test.cu into a single mex for matlab to call by using makefile. Back when the codes were developing, cuda has to be compiled through other compilers, the makefile use nvopts.sh and nvmex. I just downloaded them from this site http://ift.tt/1JoRJxV Then I successfully get a mexa64 file, then I run the m file in matlab, but they tell me that error using mex.
In terminal, I have "FAIL test.cu 2286: cudaMemcpy an illegal memory access was encountered". Here is the error parts of that the terminal told.(since this code is too long and confidential, so please excuse me for not showing all the codes)

   else{
        //printf("use the nturn = %d \n", nturn );
        jf_gpu_memset(dev_proj, 0, nst*nturn)

        for( register int j = 0; j < 10 ; j++){
            sf2_proj_kernel_3<<<dimGrid3, dimBlock3>>>( 
                j, nx, nz, nt, ns, 
                wt, wz, dwt, dwz, 
                dev_list_num, dev_list, dev_nbins, 
                dev_weight, 
                dev_zinc,
                dev_proj,
                dev_image );    
        }

        //sf2_proj_kernel_4<<<dimGrid4, dimBlock4>>>(nx, nz, nt, ns, wz, wt, ws, ds, dt, dsd, temp_proj, dev_proj, cgeom, pa->o_is_ns_nt);
        //jf_gpu_get(pp ,temp_proj, nproj_cells)
        printf("%p,%p,%p \n",pp,dev_proj,nproj_cells);
        jf_gpu_get(pp ,dev_proj, nproj_cells)
        pp = pp + nproj_cells;
    }


adjacency matrix find if neighbores


I have some homwrok and it looks like this: Question 1 ( First program adjacency.c file ) Directed tree structure T has N nodes represented by the adjacency matrix A size NxN as follows:

A [ u ] [ v] == TRUE if and only if there is a directed arc from u to v in T , or in other words : u is the parent of v . In the following example a tree with N = 11 nodes :

tree

We obtain the following neighboring matrix :

matrix

this are the questions:

A. You must define with #define command and / or enum the N and permanent TRUE and FALSE. Typedef should be set with a character named adj_mat defines the neighboring matrix size N.

B. You must write a function called path, which accepts as a parameter adjacency matrix A and indexes of two nodes u and v and returns TRUE if and only if there is a directed path (by directional arrow) at the intersection u v, the tree is represented by a matrix A. Otherwise it returns FALSE.

For example: path (1,8) will return TRUE. The same path (1,3). On the other hand path (3,8) will FALSE.

C. First you must write a function (main) defines a variable type adj_mat, asks the user entries for this matrix, and indexes of the two nodes. The main function function call path, to see if there is a directed path between two nodes in the data. The function to print the test result output.

have to get some help guys

#include <stdio.h>

#define N 11
enum {FALSE, TRUE};
typedef int adj_mat[N][N];

int path(adj_mat A, int u, int v)
{
if(u == 0 && A[u][v] == TRUE)
return TRUE;

if(u == 0 && A[u][v] == FALSE)
return FALSE;

if(A[u][v] == FALSE)
{
--u;
return path(A, -u, v);
}

else if(A[u][v] == TRUE)
return path(A, N-1, u);
return FALSE;
}

int main()
{

int arr[N][N]= {{0,1,1,1,0,0,0,0,0,0,0},{0,0,0,0,1,1,1,1,1,0,0},
{0,0,0,0,0,0,0,0,0,1,0},{0,0,0,0,0,0,0,0,0,0,1},{0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,0,0}};
int u;
int v;
printf("please enter two numbers \n");
scanf("%d", &u);
scanf("%d", &v);
return path(arr, u, v);
;
}

The problem is at the terminal when i put 1,8 it doesnt do nothing.


How to Find all Occurances of a Substring in C


I am trying to write a parsing program in C that will take certain segments of text from an HTML document. To do this, I need to find every instance of the substring "name": in the document; however, the C function strstr only finds the first instance of a substring. I cannot find a function that finds anything beyond the first instance, and I have considered deleting each substring after I find it so that strstr will return the next one. I cannot get either of these approaches to work. Any suggestions? Thanks.

By the way, I know the while loop limits this to six iterations, but I was just testing this to see if I could get the function to work in the first place.

                    while(entry_count < 6)
                    {   
                        printf("test");
                        if((ptr = strstr(buffer, "\"name\":")) != NULL)
                        {   
                            ptr += 8;
                            int i = 0;
                            while(*ptr != '\"')
                            {   
                                company_name[i] = *ptr;
                                ptr++;
                                i++;
                            }   
                            company_name[i] = '\n';
                            int j;
                            for(j = 0; company_name[j] != '\n'; j++)
                                printf("%c", company_name[j]);
                            printf("\n");
                            strtok(buffer, "\"name\":");
                            entry_count++;
                        }   
                    }   


Detect if WM_MOUSEMOVE is caused by touch/pen


I am experimenting with WM_TOUCH and want to detect if mouse events are synthesized from touch/pen events or due to an actual mouse event.

The official solution according to MSDN is to check if the result of GetMessageExtraInfo() has the upper 24 bits set to 0xFF515700.

This works. Most of the time. If I use one finger, all is well and good, but if I use more than one, releasing the last one causes a mouse move with GetMessageExtraInfo() == 0. Also, when the window loses focus via touch, up to 3 mouse move messages with GetMessageExtraInfo() == 0 are generated.

Is there a reliable way of disambiguating between mouse, touch and pen inputs?


A program that, given a string, a width, and an empty string for ouput, centers the string in the ouput area.


The function is to return 1 if the formatting is successful and 0 if any errors, such as string length greater than width, are found. I'm getting errors though? What's wrong? I don't think I'm calling it right either...

#include <stdio.h>

int main()
{
    int dummy, value = 0;

    formatString(value);

    scanf_s("%d",&dummy);
    return 0;
}

int formatString (char *in, 
              char *out, 
              int   width)
{
//Local Declarations
int spaces;
char *start;
char *walker;
int value;

spaces = (width – 1) – strlen(in);
if (spaces < 0)
{
    value = 0;
}
else
{
    start = out + (spaces / 2);
    for (walker = out; walker < start; walker++)
       *walker = ' ';
    strcpy (start, in);

    for (walker = out + strlen(out); 
         walker < out + width – 2; 
         walker++)
       *walker = ' ';
    *walker = ‘\0’;
}
    return value;
}


josephus permutation segmentation fault


I am trying to solve the Josephus permutation using a binary search tree. I implemented the functions os_select and os_delete from Cormen, and I have the following problem:

typedef struct node
{
    int key;
    struct node *left;
    struct node *right;
    int size; //dimensiunea subarborelui cu radacina in key
} node;

void josephus(int n, int m)
{
    node *root=build_tree(v,0,n-1); //this is tested, works perfectly
    int k,j=1;
    for(k=n;k>=1;k--)
    {
        j=((j+m-2)%k)+1;
        node *x=os_select(root,j);
        printf("%d ",x->key);
        decSize(x,j);
        os_delete(root,x->key);
    }
    //afisare_in_preordine(root,0);
}

When I run the program, I get a segmentation fault inside the os_select function:

node *os_select(node *x,int i)
{
    int r=x->left->size+1; //i get the segmentation fault here...
    if (i==r)
    {
        return x;
    }
    else
    {
        if(i<r)
        {
            return os_select(x->left,i);
        }
        else
        {
            return os_select(x->right,i-r);
        }
    }
}

If you need anymore pieces of code that I should add, please let me know.


How to compile picoProlog from source code?


I am a student in Computer Science, and I am learning about logic programming with Prolog.

I have found an interesting Prolog interpreter, http://ift.tt/1DvB44O.

To know more about Prolog, I am trying to compile their source code, but I failed.

In this web page, they said:


The interpreter source is written in a minimal dialect of Pascal, avoiding many features including pointers, but using macros to overcome some of Pascal's limitations, in a style inspired by Kernighan and Plauger's book Software tools in Pascal. It comes with a translator from the Pascal dialect into C that can be used to build the interpreter and also source for the macro processor that is needed.

To build the interpreter on a Linux machine, just extract the tar file and type make. The building happens in several stages:

  1. First, the Pascal-to-C translator ptc is built from C source, including a lexer and parser written with lex and yacc. The file README gives some details of the very restricted Pascal subset accepted by this translator.
  2. Next, ptc is used to build the macro processor ppp.
  3. Finally, the picoProlog interpreter is built from the source code in the file pprolog.x by first expanding macros using ppp to obtain a file pprolog.p, then translating to C with ptc, and lastly compiling the C code.

Text and software copyright © J. M. Spivey, 1996, 2002, 2010.


They said about compiling on Linux only, so I don't know how to compile this source code in Windows machine. Can I compile it with Turbo Pascal 7.0, or Free Pascal 2.6.4 (without any requirement) on Windows XP? Can you remove some part of script for Pascal compiling only?


Produce incorrect value from a given correct value and set of invalid chars


I need to create the Invalid values for a given attribute like ID that has only correct value ASP-101. All values other than this like ASP-101! or ASP-101# or !SP-101 or ASP+101 or ASP-10# .. etc are incorrect. A file with invalid chars is given, Special characters file invalidchars.txt has :

#
$
%
^
&
*
(
)
-
_
+
=
{
}
[
]
\
/
|
:
;
"
'
?
>
<
.
,

 /

and main.c has the code:

#include<stdio.h>
#include<string.h>
#include<malloc.h>
#include<stdlib.h>

int main()
{

    FILE *fp_char,*fp_test;
    char aspid[] = "ASP-101";
    char *asp;
    char arr[2];
    char invalid_chars;


    fp_char = fopen("invalidchars.txt","r");
    fp_test = fopen("test.txt","w");

    if(fp_test == NULL || fp_char == NULL)
    {
        printf("cannot open file.\n");
        return;
    }


    asp = (char *)malloc(sizeof(char)*(strlen(aspid)+2));
    strcpy(asp,aspid);


    while((invalid_chars = fgetc(fp_char)) != EOF) 
    {
        arr[0]=invalid_chars;
        strcat(asp,arr);
        fprintf(fp_test,"%s\t",asp);
        memset(asp,0,strlen(aspid));
        strcpy(asp,aspid);
    }

    fclose(fp_char);
    fclose(fp_test);
    return 0;
}

In this I have covered the appending special char in the end and produce incorrect value. But how to generate others cases for incorrect value for attribute.

Somebody help is admired a lot . Any idea will help me to do this......