gerard4143 371 Nearly a Posting Maven

OK, here's a simple client/server example that requests a file.

client.c

#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <strings.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>

#define DEFAULT_PROTOCOL 0
#define PORT 50000
#define MAXLINE 4096

int main(int argc, char**argv)
{
  int clientfd, tot = 0, n = 0;
  char recvline[MAXLINE];
  struct sockaddr_in servaddr;
  
  if ( argc != 3 )
  {
	fputs("usage error - a.out <IPaddress> <Filename>\n", stderr);
	exit(EXIT_FAILURE);
  }
  
  if ((clientfd = socket(AF_INET, SOCK_STREAM, DEFAULT_PROTOCOL)) < 0)
  {
	perror("socket");
	exit(EXIT_FAILURE);
  }
  
  bzero(&servaddr, sizeof(servaddr));
  servaddr.sin_family = AF_INET;
  servaddr.sin_port = htons(PORT);
  
  if ((inet_pton(AF_INET, argv[1], &servaddr.sin_addr.s_addr)) <= 0)
  {
	fputs("conversion error!\n", stderr);
	exit(EXIT_FAILURE);
  }
  
  if ((connect(clientfd, (const struct sockaddr*)&servaddr, sizeof(servaddr))) < 0)
  {
	perror("connect");
	exit(EXIT_FAILURE);
  }
  
  write(clientfd, argv[2], strlen(argv[2]));
  
  shutdown(clientfd, SHUT_WR);
  
  while ((n = read(clientfd, recvline, MAXLINE)) > 0)
  {
	recvline[n] = '\0';
	tot += n;
	fputs(recvline, stdout);
  }
  if ( n < 0 )
	fputs("read error!\n", stderr);
  fprintf(stdout, "client read %d bytes!\n", tot);
  close(clientfd);
  exit(EXIT_SUCCESS);
}

server.c

#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <strings.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>

#define DEFAULT_PROTOCOL 0
#define PORT 50000
#define MAXLINE 4096
#define PATH_SIZE 128

int main(int argc, char**argv)
{
  int listenfd, connfd, val = 1;
  char recvline[MAXLINE];
  struct sockaddr_in servaddr;
  
  signal(SIGCHLD, SIG_IGN);
  
  if ((listenfd = socket(AF_INET, SOCK_STREAM, DEFAULT_PROTOCOL)) < 0)
  {
	perror("socket");
	exit(EXIT_FAILURE);
  }
  
  setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
  
  bzero(&servaddr, sizeof(servaddr));
  servaddr.sin_family = AF_INET;
  servaddr.sin_port = htons(PORT);
  servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
  
  if ((bind(listenfd, (const struct sockaddr*)&servaddr, sizeof(servaddr))) < 0)
  {
	perror("bind");
	exit(EXIT_FAILURE);
  }
  
  if ((listen(listenfd, 5)) < 0)
  {
	perror("listen"); …
gerard4143 371 Nearly a Posting Maven

Right. But I want to read bits. You see, my task is to develop some kind of a crypto system which means I got to do a lot of bit substitutions and permutations in which case I certainly have to mask bits out.

You can't read bits outright, the hardware can only address bytes. If you need to interrogate bits, you must rely on masking operations or bit operators.

gerard4143 371 Nearly a Posting Maven

This should get ptr pointing at the first element of buffer.

unsigned short* ptr = (unsigned short*)buffer;

Please note, when you increment ptr(or access an element with an index ptr), the address increments by sizeof(unsigned short) and not by sizeof(unsigned char).

gerard4143 371 Nearly a Posting Maven

Once present, this correlation between the file and the memory space permits applications to treat the mapped portion as if it were primary memory.

to me this says "the program is still on the hard drive but the pc thinks its in RAM" i dont understand the purpose of this then

Could you post the link that the above statement is taken from.

gerard4143 371 Nearly a Posting Maven

Check out the strace of a 'hello, world' program, especially line 9 which opens the standard C library /lib64/libc.so.6, the next line 10 which reads the file and the next line 12 which maps the code from /lib64/libc.so.6 into memory.

execve("./test", ["./test"], [/* 83 vars */]) = 0
brk(0)                                  = 0x18dc000
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7ffb72108000
access("/etc/ld.so.preload", R_OK)      = -1 ENOENT (No such file or directory)
open("/etc/ld.so.cache", O_RDONLY)      = 3
fstat(3, {st_mode=S_IFREG|0644, st_size=123320, ...}) = 0
mmap(NULL, 123320, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7ffb720e9000
close(3)                                = 0
open("/lib64/libc.so.6", O_RDONLY)      = 3
read(3, "\177ELF\2\1\1\3\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\20\354\1\0\0\0\0\0"..., 832) = 832
fstat(3, {st_mode=S_IFREG|0755, st_size=1711148, ...}) = 0
mmap(NULL, 3586216, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7ffb71b81000
mprotect(0x7ffb71ce4000, 2093056, PROT_NONE) = 0
mmap(0x7ffb71ee3000, 20480, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x162000) = 0x7ffb71ee3000
mmap(0x7ffb71ee8000, 18600, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7ffb71ee8000
close(3)                                = 0
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7ffb720e8000
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7ffb720e7000
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7ffb720e6000
arch_prctl(ARCH_SET_FS, 0x7ffb720e7700) = 0
mprotect(0x7ffb71ee3000, 16384, PROT_READ) = 0
mprotect(0x7ffb72109000, 4096, PROT_READ) = 0
munmap(0x7ffb720e9000, 123320)          = 0
fstat(1, {st_mode=S_IFCHR|0600, st_rdev=makedev(136, 1), ...}) = 0
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7ffb72107000
write(1, "Hello, World!\n", 14Hello, World!
)         = 14
exit_group(0)                           = ?
gerard4143 371 Nearly a Posting Maven

Why memory maps? Exe's, Dll's or shared objects need to be mapped into memory before they can be execute, you can't execute code from a drive it must be mapped into memory(RAM). Is it better? Depends, what are you reading and what are you doing with it.

gerard4143 371 Nearly a Posting Maven

i know that this line is causing the segmentation fault

if(open = fopen("/home/user/www/home.html", "rb"))

could it be the privileges set on the file ?

First, does the file exist? If it exists, can you open it? Try opening the file with an editor. Finally, what system are you running this code on?

gerard4143 371 Nearly a Posting Maven

Enumerated types are constant integrals, they are created by the compiler, so you can't convert a string to an enumerated type.

Your enum

enum MyType{
   Saw, Saw2, Saw3
};

the compiler would assign these values.

Saw = 0, Saw2 = 1, Saw3 = 2

gerard4143 371 Nearly a Posting Maven

you could create an 18-byte character array, assuming 8 bits to the byte. Files do not contain bits -- they contain bytes, and the number of bits to the byte is operating system dependent. On MS-Windows and *nix there's 8 bit to the byte. So 128 bits would be 128/8 = 18 bytes.

That's odd, I always thought byte size was a feature of the hardware and not the operating system.

gerard4143 371 Nearly a Posting Maven

Well if I had to do this I would create an array like(this assumes 64 bit longs)

unsigned long mya[2] = {0,0};/*128 bits initialized to zero*/

and read the data like so

fread(mya, sizeof(unsigned long), 2, fileStream);/*read 128 bits*/
gerard4143 371 Nearly a Posting Maven

Well you could find out the hex value of 2584 and then place the appropriate values in the correct array elements or you could extend your array to five elements and create a c-string and use the function atoi() like below.

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

int main()
{
  char ch[5] = {'2','5','8','4','\0'};
  int ans = atoi(ch);
  
  fprintf(stdout, "ans->%d\n", ans);
  return 0;
}
gerard4143 371 Nearly a Posting Maven

Why not read 128 bits and mask out the unwanted data.

gerard4143 371 Nearly a Posting Maven

Line 19, your if statement is incorrect, you want the code executed if fopen succeeds. The way you have it now, the code is executed when fopen fails.

gerard4143 371 Nearly a Posting Maven
while ((write(connfd, recvline, fread(recvline, sizeof(char), MAXLINE, fd))))
	  {}

This is a loop that first fread's into the buffer recvline and then writes the buffer(recvline) to the client connfd.

gerard4143 371 Nearly a Posting Maven

Read this

http://gcc.gnu.org/onlinedocs/cpp/Pragmas.html

It pretty much explains it in the simplest terms

gerard4143 371 Nearly a Posting Maven

Right away, I would use array notation.

information = r_ptr[locationNumber].y;

Your 2D array. Is that a pointer to pointer like

struct  ruudud **r_ptr;

or

struct  ruudud r_ptr[4][4];
gerard4143 371 Nearly a Posting Maven

Adding elements to a vector isn't automatic with the array subscript, if the element doesn't exist and you try an access it, you may get a seg fault. One way to add elements is the pushback member function.

gerard4143 371 Nearly a Posting Maven

Are you sure your vector has enough elements?

gerard4143 371 Nearly a Posting Maven

Line 5 in main, don't #include "quicksort.c". You should only include header files.

gerard4143 371 Nearly a Posting Maven

Try looking at the code below.

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

void myfunction(int **array1, int **array2)
{
  int i = 0, j = 0;
  
  for (i = 0; i < 4; ++i)
  {
	for (j = 0; j < 4; ++j)
	{
	  fprintf(stdout, "ans->%d\n", array1[i][j]);
	  fprintf(stdout, "ans->%d\n", array2[i][j]);
	}
  }
  
}

int main(int argc, char**argv)
{
  int i = 0, j = 0;
  int **myarray1;
  int **myarray2;
  
  myarray1 = (int**)malloc(4 * sizeof(int*));
  myarray2 = (int**)malloc(4 * sizeof(int*));
  
  for (i = 0; i < 4; +++i)
	myarray1[i] = (int*)malloc(4 * sizeof(int));
  
  for (i = 0; i < 4; +++i)
	myarray2[i] = (int*)malloc(4 * sizeof(int));
  
  for (i = 0; i < 4; ++i)
  {
	for (j = 0; j < 4; ++j)
	{
	  myarray1[i][j] = i + j;
	  myarray2[i][j] = i + j;
	}
  }
 
  myfunction(myarray1, myarray2);
  /*free memory here*/
  return 0;
}
gerard4143 371 Nearly a Posting Maven

If your using bits then maybe you should consider a structure with bits fields.

struct my_bits
{
  unsigned int one:1;
  unsigned int two:1;
  unsigned int three:1;
  unsigned int four:1;
  unsigned int five:1;
  unsigned int six:1;
  unsigned int seven:1;
  unsigned int eight:1;
  unsigned int nine:1;
  unsigned int ten:1;
};
gerard4143 371 Nearly a Posting Maven

Try creating your function like so

void myfunction(int array1[][4], int array2[][4])

And calling it like so

myfunction(myarray1, myarray2);
gerard4143 371 Nearly a Posting Maven

f2 passes the address of the object/value. Changes to the value itself that happen inside the body of f2 are done on the object that i points to. changes to i (the pointer) are not reflected, so when you leave the body i will point tho the original memory address even if you assigned it a new value inside the body.

You should also mention, the pointer value is copied in the function call. Many a rookie, think that pointers are handled special in function calls, they are variables that hold memory locations and the value that the pointer holds is copied in a function call.

gerard4143 371 Nearly a Posting Maven

When you pass a variable's address via a pointer, your just saying this is where I am. I hold the location of the variable in my value or I hold the value NULL.

gerard4143 371 Nearly a Posting Maven

Your not guaranteed how the arguments in printf are evaluated, left to right, right to left..It depends on the C compiler your using!!!!!!!!!!!!!!!!!!!!!(many ! so the reply is urgent).

gerard4143 371 Nearly a Posting Maven

Here's a simple server which receives a filename from a client, opens the file and writes the data to the client. If the file can't be found, it writes an error message to the client. From this bare shell, you should be able to create your simple web server.

#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <strings.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>

#define DEFAULT_PROTOCOL 0
#define PORT 50000
#define MAXLINE 4096
#define PATH_SIZE 128

int main(int argc, char**argv)
{
  int listenfd, connfd, val = 1;
  char recvline[MAXLINE];
  struct sockaddr_in servaddr;
  
  signal(SIGCHLD, SIG_IGN);
  
  if ((listenfd = socket(AF_INET, SOCK_STREAM, DEFAULT_PROTOCOL)) < 0)
  {
	perror("socket");
	exit(EXIT_FAILURE);
  }
  
  setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
  
  bzero(&servaddr, sizeof(servaddr));
  servaddr.sin_family = AF_INET;
  servaddr.sin_port = htons(PORT);
  servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
  
  if ((bind(listenfd, (const struct sockaddr*)&servaddr, sizeof(servaddr))) < 0)
  {
	perror("bind");
	exit(EXIT_FAILURE);
  }
  
  if ((listen(listenfd, 5)) < 0)
  {
	perror("listen");
	exit(EXIT_FAILURE);
  }
  
  for (;;)
  {
	connfd = accept(listenfd, NULL, NULL);
	
	if (fork())
	{
	  close(connfd);
	}
	else
	{
	  int n = 0, i = 0;
	  char filename[PATH_SIZE];
	  FILE *fd = NULL;
	  char err_msg[] = "Could not open ";
	  char newline[] = "\n";
	  
	  close(listenfd);
	  
	  while ((n = read(connfd, &filename[i], (PATH_SIZE - i))) > 0)
	  {
		i += n;
	  }
	  filename[i] = '\0';
	  
	  if (!(fd = fopen(filename, "r")))
	  {
		write(connfd, err_msg, strlen(err_msg));
		write(connfd, filename, strlen(filename));
		write(connfd, newline, strlen(newline));
		exit(EXIT_FAILURE);
	  }
	  
	  while ((write(connfd, recvline, fread(recvline, sizeof(char), MAXLINE, fd))))
	  {}
	  
	  fclose(fd);
	  close(connfd);
	  exit(EXIT_SUCCESS);
	}
  }
  return EXIT_SUCCESS;
}
gerard4143 371 Nearly a Posting Maven

I'm starting out with Qt4 and so far I'm impressed with the libraries and supporting tools/IDE like Qt Designer, Qt Creator, Kdevelop.

gerard4143 371 Nearly a Posting Maven

I am not familiar this topic of C language but I have backgrounds on some basic from the language. I hope you can help me with this topic.

basic math test

What is this?

gerard4143 371 Nearly a Posting Maven

Try it with 2 char arrays that you declare one right after the other, which don't have to adjoin in memory but with such a small program they often do, then write more into the second one than it can hold. If you print it out it's clobbered the first one.

I was assumed, he was only taking seven characters from the stream and placing them in the array and the terminating it(the array) with '\0'. In this instance, the remaining characters would be in the stream.

In the scenario your describing, you would indeed have a buffer overflow and possible data corruption.

gerard4143 371 Nearly a Posting Maven

If your interested in the makings of C++ code the may I recommend a book by Stanley Lippman - Inside The C++ Object Model. Its a great read and addresses many your questions.

gerard4143 371 Nearly a Posting Maven

If someone inputted a string that was 15 letters long, would the leftover characters after the null terminator be discarded? or would they remian in the input stream?

And on one last note: is there a way to expand my character array size once it's defined?

Your first question. Yes the characters remain in the stream.

Your second question. No you can't change the size of a static array but you can create a dynamic array with new and that array can be changed(or recreated).

gerard4143 371 Nearly a Posting Maven

thanku for ur information. I know it is stored in read only memory and i also know that we can't alter a value but how it worked in Turbo C thats my question.

Why it worked in Turbo C, read Rubberman's post.

gerard4143 371 Nearly a Posting Maven

so do i need to change fread to just read ?

No, its O.K. to keep the fread().

gerard4143 371 Nearly a Posting Maven

Could you indicate which line is 89.

gerard4143 371 Nearly a Posting Maven

Try moving line 9 to line 6.

gerard4143 371 Nearly a Posting Maven

Well, you could post the code for starters.

gerard4143 371 Nearly a Posting Maven

I'm not sure what you mean by extract a value. Do you mean get the value?

This gets the value of the nth element of array.

int value = array[n];

A note on style, search functions usually return the address of first element match. Your function returns the value of the last one. Why does this matter? Well if you return the address of the first match, it gives a point to search for more matches.

gerard4143 371 Nearly a Posting Maven
open_ptr = fopen("/home/user/www/home.html","r");
	if(open_ptr == NULL){
	printf("ERROR OPENING FILE"); 
	}
	while((n = fread(buffer,1,sizeof buffer, open_ptr)) > 0)
	{
	
	fwrite(new_sock,buffer,n,open_ptr); 
	
	}

i do not know what i am missing ?

Try changing line 8 back to what it was

n = write( new_sock,buffer,n);/*note only write the number of bytes read*/

Now check the value of n with each write.

gerard4143 371 Nearly a Posting Maven

somehow it did compile the server listens when i try to connect to it via my web browser it just disconnects

You have to use open if your going to use write/read. The reason your program compiled with open was that 'r' is a character value that can be implicitly converted to int. Like I said in the first post, check for success or failure on calls to open and write.

gerard4143 371 Nearly a Posting Maven

i cant seem to send my html file through a socket, when vere i connect to the server via web browser http://localhost:7000 it just freezes. and the server stops

open_ptr = open("/home/user/www/home.html",'r'); 
  
         while((n = read(open_ptr,buffer,256)) > 0)
     {
  
          n = write( new_sock,buffer,256); 

     }
  
         close(open_ptr);   
         return 0; 
      }

Are you checking the results of the write function? Is it returning -1 and is the errno set?
Also, did you check to see if the file opened correctly?... What are you passing to open, how did this even compile?
Here's the definition of open.

int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);

Your using open like it was fopen.

FILE *fopen(const char *path, const char *mode);
gerard4143 371 Nearly a Posting Maven

But why didnt it work for the float but the other strings had % but it still wrote to the file anyway. Why is that?

Because c-string's are just arrays of characters delimited with '\0', so this means passing a c-string's variable name is the same as passing the address of the variable. It works, but it looks odd and my compiler fired off a warning about a type miss match.

gerard4143 371 Nearly a Posting Maven

But why didnt it work for the float but the other strings had % but it still wrote to the file anyway. Why is that?

Didn't notice the other fprintf's, you should drop the & unless your looking to print the address of a variable.

Also gets().. Never use gets always use fgets().

From my help files

Never use gets(). Because it is impossible to tell without know‐
ing the data in advance how many characters gets() will read, and
because gets() will continue to store characters past the end of
the buffer, it is extremely dangerous to use. It has been used to
break computer security. Use fgets() instead.

gerard4143 371 Nearly a Posting Maven

Line 33.

fprintf(ci,"Amount paid to date: %.2f\n",& info.apaid);

Your passing the address of info.apaid to fprintf.. It should be.

fprintf(ci,"Amount paid to date: %.2f\n", info.apaid);

Also your using fflush() incorrectly, you should never flush an input stream. If you want to flush all possible streams then call fflush(NULL).

gerard4143 371 Nearly a Posting Maven

I omitted the cin portion, is that what you mean?

Yeah I guess you could do it that way... something like below.

#include <iostream>

#define ARR_SIZE 8

int main()
{
  int i = 0;
  char input[ARR_SIZE];
  
  while(input[i] = std::cin.get() , input[i]  != '\n' && i < (ARR_SIZE - 1))
  { 
	i++;
  }
  
  input[i] = '\0';

  std::cout<<input<< std::endl;;
  return 0;
}
gerard4143 371 Nearly a Posting Maven
gerard4143 371 Nearly a Posting Maven

Dynamic libraries can be linked to a running process - so the linking is considered dynamic.
Static libraries are linked to a program at compile time and don't change during execution - the linking is fixed so its static.

gerard4143 371 Nearly a Posting Maven

input[8] is not the last member of your array, input[7] is.

When you declare the array you put the size, when you use the array, you put the index.

After taking in the input, you could say

if(input[7] != '\0')
   input[7] = '\0'

What I think you were doing is trying to march down the string, which you can do by

int i = 0;
while(input[i] != '\0')
{ 
   cout<<input[i]<<" ";
   i++;
}
(it could be a for loop too, I was just using while because you did)

Shouldn't your code initialize input to a value that is not '\0' first.

gerard4143 371 Nearly a Posting Maven

I would look up the functionality of getline().

http://www.cplusplus.com/reference/iostream/istream/getline/

gerard4143 371 Nearly a Posting Maven

You have a number of questionable things in that function.

float calcActualAmount(float amountP, int nrChildrenP)
{

  float leftToSpend;
  if (calcAllowedPerChild(nrChildrenP) > 180)
	amountP = 180;
  else if (calcAllowedPerChild(nrChildrenP) < 180)
	leftToSpend = calcAllowedPerChild(nrChildrenP) - 100;
  
  do
  {
	for (int i = 1; i <= 5; i++)
	{
	  switch (i)
	  {
	  case 1: leftToSpend -= TOOTHBRUSH;
	  break;
	  case 2: leftToSpend -= HIGHLIGHTERS;
	  break;
	  case 3: leftToSpend -= CRAYONS;
	  break;
	  case 4: leftToSpend -= NOTEBOOK;
	  break;
	  case 5: leftToSpend -= PEN;
	  break;

	  amountP = calcAllowedPerChild(nrChildrenP) - leftToSpend;/*why are you calling this agin?*/

	  }
	}

  return amountP;
  }
  while (leftToSpend == 0);/*whats the purpose of this?*/
}
gerard4143 371 Nearly a Posting Maven

Line 29. Why do you have a closing brace there?