C primeri

Teme koje se tiču programiranja

Moderator: Urednik

Post Reply

offline

Post Napisano: 22 Nov 2009, 11:42


Vas prvi C program, za ovo ce vam biti potreban text editor i GNU C compiler Collection (GCC)
Otvorite text editor i upisite sledece

Code: Select all

#include <stdio.h> 

int main()
{
   printf("Hello, world!\n");
   return 0;
}
Sacuvajte ovo kao hello.c, i sada imate izvorni kod vaseg prvog programa, da bi taj program mogao da se izvrsava na vasem kompjuteru potrebno ga je prevesti
Za to koristimo GCC

Code: Select all

$ gcc hello.c -o hello
Kada se prevede potrebno ga je pokrenuti sa

Code: Select all

$ ./hello
i trebalo bi da dobijete izlaz

Code: Select all

Hello, world!
Par vaznih stvar, kada nesto prevodite moze se desiti da od kompajlera dobijete neke poruke tipa error, warning (greske, upozorenja) i dobijete liniju u izvornom file-u na kojoj su moguce greske.
error su sintaksne greske kada kompajler vrati error prevodjenje programa nije moguce.
warning (logicke greske) program ce biti preveden ali moze se dogoditi da rezultate koje ste ocekivali nece biti tacni, sto nije uvek slucaj. (verovatno ste prevodili neki program za vas Slackware gnu/linux i u toku prevodenja dobili neke warning poruke, a program na kraju opet radio kako treba.

Nadam se da nema puno gresaka u ovom tekstu, ako ih ima slobodno prijavite bice ispravljeno.
Toliko za sad
Last edited by branko on 22 Nov 2009, 12:12, edited 1 time in total.



offline

Post Napisano: 22 Nov 2009, 12:23


Malo cu pokusati pojasniti neke osonovne stvari
#include je pred procesorska direktiva koja ce ukljuciti stdio.h (skr. standard input/output header)
U njemu su definisane neke osnovne U/I funkcije kao sto je printf koju smo koristili u gornjem primeru sluzi za prikaz poruka i podataka na ekranu.
Svaki program mora da ima bar jednu funkciju i to main{ }  
- Svaka funkcija se sadrzi od povratne vrednosti u gornjem primeru int (skr. Integer) Integer je tip podatka (celobrojna vrednost). Velicine 2/4 Bajtova
- Imena funkcije main u ovom slucaju
- liste ulaznih argumenata ()
- tela funkcije {}
Last edited by branko on 22 Nov 2009, 12:34, edited 1 time in total.



offline

Post Napisano: 26 Feb 2010, 10:08


Par promenljivih i osnovne matematicke operacije

Code: Select all

#include <stdio.h>

int main(void)
{
   int a,b, res;   // deklaracija promenljivih tipa INT (integer velicine 2/4 bajta)
   printf("Unesite vrednosti za a b: ");
   scanf("%d %d", &a, &b);   // Uzimanje podataka od korisnika i upis na lokacije a, b
   printf("Uneli ste a = %d i b = %d", a, b);  // Pregled unetih vrednosti
   res = a + b;   // dodela vrednosti zbira a i b promenljivoj res 
   printf("\nSabrani a + b = %d\n", res);  // Prikaz rezultata (vrednosti promenljive res)
   return 0;
}
Ovaj jednostavan sabirac radi samo sa celim brojevima.

scanf("%d %d", &a, &b);  Ova linija sluzi za prihvatanje podataka, %d --> tip podatka koji se prihvata d = integer, decimalni oblik), &a --> pokazuje na adresu na koju je potrebno upisati prihvaceni podatak

printf("Uneli ste a = %d i b = %d", a, b); --> Ispisuje na ekranu liniju koja sadrzi "Uneli ste a = .....",  a, b --> pokazuju na lokaciju sa koje ce se preuzeti podatak i biti ispisan umesto %d (i kod ispisa integer-a postupak za oznaku je isti)

Ovi primeri su primeri jednog pocetnika, tako da moze biti nekih greskica itd..., sve primedbe .... slobodno objavite kao odgovor i bice ispravljeno

Nastavice se  ... :D
Last edited by branko on 25 Apr 2010, 15:48, edited 1 time in total.



Poznata ličnost
Poznata ličnost
offline

Posts: 81
Joined: 21 Mar 2007, 07:04
Location: Beograd

Post Napisano: 20 Apr 2010, 18:08


U prilogu ide i jedan PDF koji mozda nekom moze biti od koristi ( tekst je na brzinu prekopiran iz knjige, tako da moze biti da se provukla i koja greska)
Da te vidi Slobodanka kako joj kopiraš delove knjige  :grin:



offline

Post Napisano: 20 Apr 2010, 18:54


hehe  :grin:
Last edited by branko on 20 Apr 2010, 18:54, edited 1 time in total.



Administrator
Administrator
offline
User avatar

Posts: 4591
Joined: 04 Feb 2011, 20:32
Location: Beograd
Contact:

Post Napisano: 14 Dec 2011, 19:46


Ovo su neke moje C vežbice. Možda će nekome koristiti. :)

sys_dir.c - bazirano na primeru iz GNU libC dokumentacije. ls ili dir, samo bez opcija.

Code: Select all

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

int main(int argc, char **argv)
{
	char *buffer;
	size_t size = 2048;
	DIR *wd;
	struct dirent *distruct;

	/* Try to allocate the memory for the buffer */
	buffer = (char *) malloc (size);
	if (buffer == NULL)
		fprintf(stderr, "%s: %s: %d: Can't allocate memory!", 
				argv[0], "sys_dir.c", 13);

	/* Get the current dir into the buffer */
	buffer = getcwd(buffer, size);
	/* Open the directory */
	wd = opendir(buffer);
		/* If successfull */
       	if (wd != NULL)
		{
			while ((distruct = readdir(wd)))
			puts (distruct->d_name);
		}
		else
			fprintf(stderr, "%s: %s: Can't stat directory!",
					argv[0], buffer);

	closedir(wd);

	/* Free the buffer if needed */
	if (buffer != NULL)
		free(buffer);

	return 0;
}
term1.c - mala vežba glibc terminal funkcija

Code: Select all

#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <stdlib.h>

#define BUFFLEN 256

int main(int argc, char *argv[])
{
	
	static char termid[L_ctermid];
	struct termios *termstruct;
	int filedesc = STDOUT_FILENO;

	termstruct = (struct termios *) malloc (sizeof(struct termios));

	ctermid(termid);
	puts(termid);
	printf("%d\n", isatty(filedesc));	
	printf("%s\n", ttyname(filedesc));

	tcgetattr(filedesc, termstruct);

	printf("%x\n", termstruct->c_cflag);

	free(termstruct);

	return 0;
}
Igranje sa glibc memorijskim funkcijama:

Code: Select all

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

int main(int argc, char *argv[])
{
	struct test {
		int x;
		int y;
	};

	struct test *ptr;

	ptr = (struct test *) malloc (sizeof (struct test));

	if (ptr == NULL) abort();
	memset(ptr, 0, sizeof(struct test));
	printf("Size of test: %d.\n", sizeof(struct test));
	printf("Size of int: %d. \n", sizeof(int));

	free(ptr);

	return 0;
}

Code: Select all

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

int main(int argc, char *argv[])
{
	char *ptr;	
	ptr = (char *)malloc(sizeof(ptr));
	memset(ptr, 0, sizeof(ptr));
	printf("%d\n", sizeof(ptr));

	printf("Allocated %d. \n", strlen(ptr) + 1);
	free(ptr);

	return 0;
}

Code: Select all

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

#define strleng 6

int main(int argc, char *argv[])
{
	char *ptr;	
	char *copy_string;
	ptr = malloc(6);
	copy_string = malloc(256);
	
	memset(copy_string, 0, sizeof(copy_string));
	memset(ptr, 0, sizeof(ptr));

	strcpy(ptr, "proba");

	printf("String: %s, size: %d.\n", ptr, strlen(ptr));

	strcpy(copy_string, "veliki_string");

	if( (strlen(ptr)) < (strlen(copy_string)))
		ptr = realloc(ptr, (sizeof(copy_string) + 1));
	strcpy(ptr, copy_string);

	printf("String: %s, size: %d.\n", ptr, strlen(ptr));

	free(ptr);

	return 0;
}
glibc error funkcije:

Code: Select all

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

int main(int argc, char **argv)
{
	FILE *test;
	int err;

	test = fopen("readme.txt", "r");
	if (test == NULL)
	{
		err=errno;
		puts(strerror(err)); // No such file or directory
		perror("Error"); // Error: No such file or directory
	}
	else 
		fclose(test);

	return 0;

}

Code: Select all

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <error.h>


int main(int argc, char **argv)
{
	FILE *test;
	int err;

	test = fopen("readme.txt", "r");
	if (test == NULL)
	{
		err=errno;
		error(0, err, "The program %s failed", argv[0]);
		error_at_line(1, err, __FILE__, __LINE__, "The program failed", argv[0]);
	}
	else 
		fclose(test);


	return 0;

}
Mali standardni Unix alati bazirani na Unix V7 manual stranama:

sleep

Code: Select all

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

/* V7 limit */
#define MAXSEC 65536

/* Print the usage info and exit unsuccessfully */
void usage(void)
{
	puts("Usage: sleep SECONDS");
	exit(-1);
}

int main(int argc, char **argv)
{
	if (argc != 2)
	{
		/* We accept only 1 argument - number of seconds 	*/
		/* So if more or less, print usage info & bail out.	*/
		usage();
	}
	else
	{
		/* This part executes only if argc == 2 */
		int k = 0;
	
		/* Check atoi output */
		if ((k = atoi(argv[1])) == 0)
			usage();
		else
		{
			/* Check for the maximal value */
			if (k < MAXSEC)
				sleep(k);
			else
			{
				fprintf(stderr, "Error: number of seconds too large!\n");
				usage();
			}
		}
	}

	return 0;
}
cwd

Code: Select all

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

#define MAXPATHNAME 1024

int main(int argc, char **argv)
{
	char currpath[MAXPATHNAME];
	if ((getcwd(currpath, MAXPATHNAME)) == NULL)
		perror("Error");
	
	puts(currpath);

	return 0;
}
echo

Code: Select all

#include <stdio.h>

int main(int argc, char **argv)
{
	int nnl = 0;
	int cnt = 0;

	/* process the arguments */
	for(cnt = 1; cnt < argc; cnt++)
	{
		/* in case of '-n', set nnl to > 0 */
		if (argv[cnt][0] == '-' && argv[cnt][1] == 'n' && argv[cnt][2] == '\0')
			nnl++;
		else
		{
			/* print out user arguments */
			fputs(argv[cnt], stdout);
			if (cnt != argc - 1)
				fputs(" ", stdout);
		}
	}

	/* if not '-n' */
	if (nnl == 0)
		fputs("\n", stdout);

	return(0);
}
cat

Code: Select all

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

int main(int argc, char **argv)
{
	int cnt = 0, temp = 0, status = 0;
	FILE *istream;

	/* 
	 * If no arguments, check for input from
	 * stdin, than display every character
	 * to stdout. Otherwise, display files
	 * specified in command line arguments.
	 */
	if (argc == 1)
	{
		while((temp = fgetc(stdin)) != EOF)
			fputc(temp, stdout);
	}
	else
	{
		/*
		 * Browse through all the arguments 
		 */
		for (cnt = 1; cnt < argc; cnt++)
		{
			/* 
			 * Try to open the file, otherwise
			 * exit with an error message
			 */
			istream = fopen(argv[cnt], "r");
			status = errno;
			if (istream == NULL)
			{
				fprintf(stderr, "%s: %s: %s\n",
						argv[0], argv[cnt], strerror(status)); 
				break;
			}

			/* 
			 * get a character at the time from specified
			 * file and display it to stdout.
			 */
			while((temp = fgetc(istream)) != EOF)
				fputc(temp, stdout);

			
			fclose(istream);
		}
	}

	return (0);
}
sleep

Code: Select all

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

/* V7 limit */
#define MAXSEC 65536

/* Print the usage info and exit unsuccessfully */
void usage(void)
{
	puts("Usage: sleep SECONDS");
	exit(-1);
}

int main(int argc, char **argv)
{
	if (argc != 2)
	{
		/* We accept only 1 argument - number of seconds 	*/
		/* So if more or less, print usage info & bail out.	*/
		usage();
	}
	else
	{
		/* This part executes only if argc == 2 */
		int k = 0;
	
		/* Check atoi output */
		if ((k = atoi(argv[1])) == 0)
			usage();
		else
		{
			/* Check for the maximal value */
			if (k < MAXSEC)
				sleep(k);
			else
			{
				fprintf(stderr, "Error: number of seconds too large!\n");
				usage();
			}
		}
	}

	return 0;
}


Jednostavno. :)



Administrator
Administrator
offline
User avatar

Posts: 4591
Joined: 04 Feb 2011, 20:32
Location: Beograd
Contact:

Post Napisano: 14 Dec 2011, 19:50


"cevovodi" ili ti pajpovi (LPG). :)

Code: Select all

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>


int main(int argc, char *argv[])
{
	int npipe[2];
	int child;
	char buf[5];

	if (pipe(npipe))
	{
		perror("Pipe failed");
		return 30;
	}
	else
	{
		puts("pipe opened");
	}

	child = fork();
	printf("PID: %d\n", child);
	if (child < 0)
	{
		perror("fork failed");
		return 31;
	}
	else if (child == 0)
	{
		puts("fork succeded");

		close(npipe[0]);
		puts("Writing to pipe from the child");
		write(npipe[1], "test", 5);

		puts("Duplicating stdin"); 
		dup(npipe[0]);
		puts("replacing with echo stdin");
		execlp("echo", "echo", NULL);

		exit(0);
	}
	else
	{
		close(npipe[1]);
		puts("reading from parent");
		read(npipe[0], buf, sizeof(buf));
		puts("writing test from parent");
		puts(buf);
	}

	return 0;
	
}

Code: Select all

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

#define MAXSTR 5

int main(void)
{

	int n;
	FILE *npipe;
	char *strings[MAXSTR] = {"echo", "bravo", "alpha",
			"charlie", "delta"};

	npipe = popen("sort", "w");
	if (npipe == NULL)
	{
		perror("popen");
		exit(30);
	}

	for(n = 0; n < MAXSTR; n++)
	{
		fputs(strings[n], npipe);
		fputc('\n', npipe);
	}

	pclose(npipe);

	return 0;
}

Code: Select all

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

int main(int argc, char *argv[])
{
	FILE *pin, *in;
	char buf[80];

	if(argc !=3)
	{
		fprintf(stderr, "prog [command] [filename]\n");
		exit(1);
	}

	in = fopen(argv[2], "rt");
	if (in == NULL)
	{
		perror("fopen");
		exit(1);
	}

	pin = popen(argv[1], "w");
	if (pin == NULL)
	{
		perror("popen");
		exit(1);
	}

	do
	{
		fgets(buf, 80, in);
		if (feof(in)) break;

		fputs(buf, pin);
	}
	while (! feof(in));

	fclose(in);
	pclose(pin);

	return(0);
}



Administrator
Administrator
offline
User avatar

Posts: 4591
Joined: 04 Feb 2011, 20:32
Location: Beograd
Contact:

Post Napisano: 14 Dec 2011, 19:56


Imao sam negde još primera. :) Liste, dinamički moduli. Vežbanje sa strukturama. Ali nije mi to na ovom disku.

"zamena" za xset +r.  :grin:

Code: Select all

#include <stdio.h>
#include <stdlib.h>
#include <X11/Xlib.h>

int main(int argc, char **argv)
{
	Display *dpy = XOpenDisplay(":0");
	if (dpy == NULL)
	{
		fprintf(stderr, "Cannot connect to X server :0");
		exit (-1);
	}

	XAutoRepeatOn(dpy);

	XCloseDisplay(dpy);
	return 0;
}


Post Reply

Who is online

Users browsing this forum: No registered users and 19 guests