1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14.

Saturday, April 30, 2011

C -> Multiple Questions Part - 5

(1).What will be output if you will compile and execute the following c code?

void main(){
if(printf("cquestionbank"))
printf("I know c");
else
printf("I know c++");
}
(a) I know c
(b) I know c++
(c) cquestionbankI know c
(d) cquestionbankI know c++
(e) Compiler error

Answer: (c)
Explanation:
Return type of printf function is integer which returns number of character it prints including blank spaces. So printf function inside if condition will return 13. In if condition any non- zero number means true so else part will not execute.

(2).What will be output if you will compile and execute the following c code?

#define call(x) #x
void main(){
printf("%s",call(c/c++));
}
(a)c
(b)c++
(c)#c/c++
(d)c/c++
(e)Compiler error
Answer: (d)
Explanation:
# is string operator. It converts the macro function call argument in the string. First see the intermediate file:
test.c 1:
test.c 2: void main(){
test.c 3: printf("%s","c/c++");
test.c 4: }
test.c 5:
It is clear macro call is replaced by its argument in the string format.

(3). What will be output if you will compile and execute the following c code?

#define message "union is\
power of c"
void main(){
clrscr();
printf("%s",message);
getch();
}
(a) union is power of c
(b) union ispower of c
(c) union is
Power of c
(d) Compiler error
(e) None of these
Answer: (b)
Explanation:
If you want to write macro constant in new line the end with the character \.

(4). What will be output if you will compile and execute the following c code?

void main(){
int a=25;
clrscr();
printf("%o %x",a,a);
getch();
}
(a) 25 25
(b) 025 0x25
(c) 12 42
(d) 31 19
(e) None of these
Answer: (d)
Explanation:
%o is used to print the number in octal number format.
%x is used to print the number in hexadecimal number format.
Note: In c octal number starts with 0 and hexadecimal number starts with 0x.

(5).What will be output if you will compile and execute the following c code?

void main(){
int i=0;
if(i==0){
i=((5,(i=3)),i=1);
printf("%d",i);
}
else
printf("equal");
}
(a) 5
(b) 3
(c) 1
(d) equal
(e) None of above
Answer: (c)

(6).What will be output if you will compile and execute the following c code?

int extern x;
void main()
printf("%d",x);
x=2;
getch();
}
int x=23;
(a) 0
(b) 2
(c) 23
(d) Compiler error
(e) None of these
Answer: (c)
Explanation:
extern variables can search the declaration of variable any where in the program.

(7).What will be output if you will compile and execute the following c code?

void main(){
int a,b;
a=1,3,15;
b=(2,4,6);
clrscr();
printf("%d ",a+b);
getch();
}
(a) 3
(b) 21
(c) 17
(d) 7
(e) Compiler error
Answer: (d)
Explanation:
In c comma behaves as separator as well as operator.
a=1, 3, 15;
b= (2, 4, 6);
In the above two statements comma is working as operator. Comma enjoys least precedence and associative is left to right.

(8).What will be output if you will compile and execute the following c code?

void main(){
static main;
int x;
x=call(main);
clrscr();
printf("%d ",x);
getch();
}
int call(int address){
address++;
return address;
}
(a) 0
(b) 1
(c) Garbage value
(d) Compiler error
(e) None of these
Answer: (b)
Explanation:
As we know main is not keyword of c but is special type of function. Word main can be name variable in the main and other functions.

(9).What will be output if you will compile and execute the following c code?

#include "string.h"
void main(){
clrscr();
printf("%d %d",sizeof("string"),strlen("string"));
getch();
}
(a) 6 6
(b) 7 7
(c) 6 7
(d) 7 6
(e) None of these
Answer: (d)
Explanation:
Sizeof operator returns the size of string including null character while strlen function returns length of a string excluding null character.

(10).Write c program which display mouse pointer and position of pointer.(In x coordinate, y coordinate)?

Answer:
#include”dos.h”
#include”stdio.h”
void main()
{
union REGS i,o;
int x,y,k;
//show mouse pointer
i.x.ax=1;
int86(0x33,&i,&o);
while(!kbhit()) //its value will false when we hit key in the key board
{
i.x.ax=3; //get mouse position
x=o.x.cx;
y=o.x.dx;
clrscr();
printf("(%d , %d)",x,y);
delay(250);
int86(0x33,&i,&o);
}
getch();
}
(11).What will be output if you will compile and execute the following c code?

void main(){
int huge*p=(int huge*)0XC0563331;
int huge*q=(int huge*)0xC2551341;
*p=200;
printf("%d",*q);
}
(a)0
(b)Garbage value
(c)null
(d) 200
(e)Compiler error
Answer: (d)
Explanation:
Physical address of huge pointer p
Huge address: 0XC0563331
Offset address: 0x3331
Segment address: 0XC056
Physical address= Segment address * 0X10 + Offset address
=0XC056 * 0X10 +0X3331
=0XC0560 + 0X3331
=0XC3891
Physical address of huge pointer q
Huge address: 0XC2551341
Offset address: 0x1341
Segment address: 0XC255
Physical address= Segment address * 0X10 + Offset address
=0XC255 * 0X10 +0X1341
=0XC2550 + 0X1341
=0XC3891
Since both huge pointers p and q are pointing same physical address so content of q will also same as content of q.

(12).What will be output if you will compile and execute the following c code?

struct marks{
int p:3;
int c:3;
int m:2;
};
void main(){
struct marks s={2,-6,5};
printf("%d %d %d",s.p,s.c,s.m);
}
(a) 2 -6 5
(b) 2 -6 1
(c) 2 2 1
(d) Compiler error
(e) None of these
Answer: (c)
Explanation:
Binary value of 2: 00000010 (Select three two bit)
Binary value of 6: 00000110
Binary value of -6: 11111001+1=11111010
(Select last three bit)
Binary value of 5: 00000101 (Select last two bit).

Sunday, April 17, 2011

C - > GNU - Linux Sample Source Codes

What day of the week is July 4, 2001

#include // here include stdio.h file
#include // here include time.h file

int main(void) {
struct tm time_str;
char daybuf[20];

time_str.tm_year = 2001 - 1900;
time_str.tm_mon = 7 - 1;
time_str.tm_mday = 4;
time_str.tm_hour = 0;
time_str.tm_min = 0;
time_str.tm_sec = 1;
time_str.tm_isdst = -1;

if(mktime(&time_str) == -1)
fprintf(stderr, "Unkown -\n");
else
strftime(daybuf, sizeof(daybuf), "%A", &time_str), printf("%s\n", daybuf);

return 0;
}

Va_arg, vsnprintf(), concatenate strings

#include // here include stdio.h file
#include // here include string.h file
#include // here include stdlib.h file
#include // here include stdarg.h file

char *make_message(const char *fmt, ...);

int main(void) {
char *one = "this";
char *two = "is";
char *three = "becoming a string";
char *result = NULL;

result = make_message("%s %s %s", one, two, three);
if(result == NULL) {
fprintf(stderr, "Error - make_message(...) == NULL\n");
return 1;
} else {
printf("%s\n", result);
free(result);
}

return 0;
}

char *make_message(const char *fmt, ...) {
char *p = NULL;
size_t size = 30;
int n = 0;
va_list ap;

if((p = malloc(size)) == NULL)
return NULL;

while(1) {
va_start(ap, fmt);
n = vsnprintf(p, size, fmt, ap);
va_end(ap);

if(n > -1 && n < size)
return p;

/* failed: have to try again, alloc more mem. */
if(n > -1) /* glibc 2.1 */
size = n + 1;
else /* glibc 2.0 */
size *= 2; /* twice the old size */

if((p = realloc (p, size)) == NULL)
return NULL;
}
}

Va_arg, variable argument lists

#include // here include stdio.h file
#include // here include stdarg.h file

void foo(char *fmt, ...);

int main(void) {
int i = 50;
char str[] = "jeronimo";
char x = 'a';

printf(" foo prints: ");
foo("d", i);

printf(" foo prints: ");
foo("s", str);

printf(" foo prints: ");
foo("c", x);

return 0;
}

void foo(char *fmt, ...) {
va_list ap;
int d;
char c, *s;

va_start(ap, fmt);
while (*fmt)
switch(*fmt++) {
case 's': /* string */
s = va_arg(ap, char *);
printf("string %s\n", s);
break;
case 'd': /* int */
d = va_arg(ap, int);
printf("int %d\n", d);
break;
case 'c': /* char */
/* need a cast here since va_arg only takes fully promoted types */
c = (char) va_arg(ap, int);
printf("char %c\n", c);
break;
}
va_end(ap);
}

Using the terminfo database

#include // here include stdio.h file
#include // here include curses.h file
#include // here include term.h file

int main(void) {
int num_rows = 0, num_columns = 0;

setupterm(NULL, fileno(stdout), (int *)0);
num_rows = tigetnum("lines");
num_columns = tigetnum("cols");

printf("terminal:\ncolumns: %d\nrows %d\n", num_columns, num_rows);

return 0;
}

Using pipes as file streams, fdopen()

#include // here include stdio.h file
#include // here include unistd.h file
#include // here include sys/types.h file

#define MAXLINE 512

int main(void) {
char line[MAXLINE];
FILE *fpin = {0};
FILE *fpout = {0};
pid_t child = -1;
int fd[2] = {0};
int i = 0;

pipe(fd);

if((child = fork()) == -1) {
perror("fork");
return 1;
}

if(child == 0) {
close(fd[0]);

fpout = fdopen(fd[1], "w");
if(fpout == NULL) {
fprintf(stderr, "Error - fdopen(child)\n");
return 1;
}

for(i = 0; i < 10; i++)
fprintf(fpout, "%s\n", "jeronimooo...");

fclose(fpout);
return 0;
} else {
close(fd[1]);

fpin = fdopen(fd[0], "r");
if(fpin == NULL) {
fprintf(stderr, "Error - fdopen(parent)\n");
return 1;
}

while(fgets(line, MAXLINE, fpin) != NULL)
printf("%d: %s", i++, line);

fclose(fpin);
}

return 0;
}

Userinfo on x os from C

#include // here include pwd.h file
#include // here include stdio.h file
#include // here include unistd.h file
#include // here include sys/types.h file

int main(void) {
uid_t uid;
gid_t gid;
struct passwd *pw;

uid = getuid();
gid = getgid();

printf("I am user: %s\n", getlogin());
printf(" uid: %d\n", uid);
printf(" gid: %d\n", gid);

printf("\n");

pw = getpwuid(uid);
printf("Password entry for user %s:\n", pw->pw_name);
printf(" name : %s\n", pw->pw_name);
printf(" uid : %d\n", pw->pw_uid);
printf(" gid : %d\n", pw->pw_gid);
printf(" home : %s\n", pw->pw_dir);
printf(" shell: %s\n", pw->pw_shell);

printf("\n");

printf("Password entry for root:\n");
pw = getpwnam("root");
printf(" name : %s\n", pw->pw_name);
printf(" uid : %d\n", pw->pw_uid);
printf(" gid : %d\n", pw->pw_gid);
printf(" home : %s\n", pw->pw_dir);
printf(" shell: %s\n", pw->pw_shell);

return 0;
}

Terminal password example

#include // here include stdio.h file
#include // here include termios.h file

#define PASSMAX 8

int main(void) {
struct termios defrsett, newrsett;
char password[PASSMAX + 1];

tcgetattr(fileno(stdin), &defrsett);

newrsett = defrsett;
newrsett.c_lflag &= ~ECHO;

printf("Enter password: ");

if(tcsetattr(fileno(stdin), TCSAFLUSH, &newrsett) != 0)
fprintf(stderr, "Did not set attributes\n");
else {
fgets(password, PASSMAX, stdin);
tcsetattr(fileno(stdin), TCSANOW, &defrsett);
fprintf(stdout, "\nYou enterd %s", password);
}

return 0;
}

System uptime

#include // here include stdio.h file
#include // here include string.h file
#include // here include stdlib.h file

int main(void) {
FILE * uptimefile;
char uptime_chr[28];
long uptime = 0;

if((uptimefile = fopen("/proc/uptime", "r")) == NULL)
perror("supt"), exit(EXIT_FAILURE);

fgets(uptime_chr, 12, uptimefile);
fclose(uptimefile);

uptime = strtol(uptime_chr, NULL, 10);

printf("System up for %ld seconds, %ld hours\n", uptime, uptime / 3600);

exit(EXIT_SUCCESS);
}

Syslog hello

#include // here include stdio.h file
#include // here include unistd.h file
#include // here include syslog.h file

int main(void) {

openlog("slog", LOG_PID|LOG_CONS, LOG_USER);
syslog(LOG_INFO, "A different kind of Hello world ... ");
closelog();

return 0;
}

Strcat, concatenate strings, alloc mem

#include // here include stdio.h file
#include // here include string.h file
#include // here include stdlib.h file

char *mkconcat(char **, int);

int main(void) {
char *strings[] = { "jasmin", "is", "a", "nutcracker" };
char *result = NULL;

result = mkconcat(strings, (sizeof(strings) / sizeof(strings[0])));
if(result == NULL) {
fprintf(stderr, "Error - mkconcat == NULL\n");
return 1;
} else {
printf("%s\n", result);
free(result);
}

return 0;
}

char *mkconcat(char **list, int max) {
char *result = NULL;
int i = 0, len = 0;

/* calc. total size needed ... */
for(i = 0; i < max; i++)
len += (strlen(list[i]) + 1);

/* alloc sufficient mem ... */
result = malloc(len * sizeof(char) + 1);
if(result == NULL) {
fprintf(stderr, "Error - mkconcat -> malloc()\n");
return NULL;
}

/* concatenate strings */
for(i = 0; i < max; i++) {
if(strcat(result, list[i]) == NULL) {
fprintf(stderr, "Error - strcat()\n");
return NULL;
}

if(i < (max - 1)) { /* space only inbetween tokens */
if(strcat(result, " ") == NULL) {
fprintf(stderr, "Error - strcat()\n");
return NULL;
}
}
}

return result;
}

Some cd-rom functions

#include // here include stdio.h file
#include // here include fcntl.h file
#include // here include stdlib.h file
#include // here include unistd.h file
#include // here include sys/ioctl.h file
#include // here include linux/cdrom.h file

/*
// close
*/
int cdr_close(char *dev) {
int fd;

if((fd = open(dev, O_RDONLY|O_NONBLOCK)) == -1)
return -1;
else if(ioctl(fd, CDROMCLOSETRAY) == -1)
return -1;
else
close(fd);

return 0;
}

/*
// eject
*/
int cdr_eject(char *dev) {
int fd;

if((fd = open(dev, O_RDONLY|O_NONBLOCK)) == -1)
return -1;
else if(ioctl(fd, CDROMEJECT) == -1)
return -1;
else
close(fd);

return 0;
}

/*
// lock
// - if lock == 1, lock
// - if lock == 0, unlock
*/
int cdlock(char *dev, int lock) {
int fd;

if((fd = open(dev, O_RDONLY|O_NONBLOCK)) == -1)
return -1;
else if(ioctl(fd, CDROM_LOCKDOOR, lock) == -1)
return -1;
else
close(fd);

return 0;
}

Signal, catch Ctrl-C

#include // here include stdio.h file
#include // here include unistd.h file /* sleep(1) */
#include // here include signal.h file

void ex_program(int sig);

int main(void) {
(void) signal(SIGINT, ex_program);

while(1)
printf("sleeping .. ZZZzzzz ....\n"), sleep(1);

return 0;
}

void ex_program(int sig) {
printf("Wake up call ... !!! - Catched signal: %d ... !!\n", sig);
(void) signal(SIGINT, SIG_DFL);
}

Show,access enviroment var's

#ifndef __USE_GNU
#define _GNU_SOURCE
#endif

#include // here include stdio.h file
#include // here include unistd.h file
#include // here include stdlib.h file

int main(void) {
char **env = environ;
char pwd[256] = {0};

printf("getenv() says, go home: %s\n", getenv("HOME"));
getcwd(pwd, sizeof(pwd));
printf("getcwd says, no I am staying here: %s\n", pwd);

printf("All other enviroment var's .... \n");
for(; *env; env++)
printf("%s\n", *env);

return 0;
}

Show some pipe usage

#include // here include stdio.h file
#include // here include stdlib.h file
#include // here include unistd.h file

int main(void) {
/* the file descriptors */
int pipe_file_descr[2];

/* pipe creates a pair of file descriptors */
pipe(pipe_file_descr);

/* create a child process .... */
if(!fork()) {
/*
// dont need ``normal'' stdout() so...
// closing ``normal'' stdout
*/
close(1);

/*
// Now we make stdout of this process
// the same as pipe_file_descr[1]
// dup() `is duplicate ...'
*/
dup(pipe_file_descr[1]);

/*
// Don't need this pipe file descriptor
// since we have no input, only output for this process
// closing this file descriptor ...
*/
close(pipe_file_descr[0]);

/*
// Fire up `ls' to have some output
*/
execlp("ls", "ls", "-1", NULL);
} else {
/*
// Don't need ``normal'' stdin
*/
close(0);

/*
// making stdin the same as pipe_file_descr[0]
*/
dup(pipe_file_descr[0]);

/* again, don't need this one .. */
close(pipe_file_descr[1]);

/* count the output of `ls' ... */
execlp("wc", "wc", "-l", NULL);
}

/* done */
return 0;
}

Saturday, April 16, 2011

Regular expression

#include // here include stdio.h file
#include // here include regex.h file
#include // here include locale.h file
#include // here include string.h file
#include // here include stdlib.h file
#include // here include sys/types.h file

#define MAXLINE 2028
#define PACKAGE "regexample"

int main(int argc, char *argv[]) {
char line[MAXLINE];
int retval = 0;
regex_t re;

if(argc != 2) {
fprintf(stderr, "Usage: %s regularexpression < text.file\n", PACKAGE);
exit(EXIT_FAILURE);
}

setlocale(LC_ALL, "");
if(regcomp(&re, argv[1], REG_EXTENDED) != 0) {
fprintf(stderr, "%s: Error compiling regular expression: %s\n", PACKAGE, argv[1]);
exit(EXIT_FAILURE);
}

while((fgets(line, MAXLINE, stdin)) != NULL)
if((retval = regexec(&re, line, 0, NULL, 0)) == 0)
printf("%s", line);

regfree(&re);
exit(EXIT_SUCCESS);
}

Recursive directory walk

#include // here include ftw.h file
#include // here include stdio.h file
#include // here include sys/stat.h file

int list(const char *name, const struct stat *status, int type);

int main(int argc, char *argv[]) {
if(argc == 1)
ftw(".", list, 1);
else
ftw(argv[1], list, 1);

return 0;
}

int list(const char *name, const struct stat *status, int type) {
if(type == FTW_NS)
return 0;

if(type == FTW_F)
printf("0%3o\t%s\n", status->st_mode&0777, name);

if(type == FTW_D && strcmp(".", name) != 0)
printf("0%3o\t%s/\n", status->st_mode&0777, name);

return 0;
}

// FTW_F The object is a file
// FTW_D ,, ,, ,, ,, directory
// FTW_DNR ,, ,, ,, ,, directory that could not be read
// FTW_SL ,, ,, ,, ,, symbolic link
// FTW_NS The object is NOT a symbolic link and is one for
// which stat() could not be executed

Print some general file info

#include // here include time.h file
#include // here include stdio.h file
#include // here include stdlib.h file
#include // here include sys/stat.h file
#include // here include sys/types.h file

int main(int argc, char *argv[]) {
struct stat file_stats;

if(argc != 2)
fprintf(stderr, "Usage: fstat FILE...\n"), exit(EXIT_FAILURE);

if((stat(argv[1], &file_stats)) == -1) {
perror("fstat");
return 1;
}

printf("filename: %s\n", argv[1]);
printf(" device: %lld\n", file_stats.st_dev);
printf(" inode: %ld\n", file_stats.st_ino);
printf(" protection: %o\n", file_stats.st_mode);
printf(" number of hard links: %d\n", file_stats.st_nlink);
printf(" user ID of owner: %d\n", file_stats.st_uid);
printf(" group ID of owner: %d\n", file_stats.st_gid);
printf(" device type (if inode device): %lld\n",file_stats.st_rdev);
printf(" total size, in bytes: %ld\n", file_stats.st_size);
printf(" blocksize for filesystem I/O: %ld\n", file_stats.st_blksize);
printf(" number of blocks allocated: %ld\n", file_stats.st_blocks);
printf(" time of last access: %ld : %s", file_stats.st_atime, ctime(&file_stats.st_atime));
printf(" time of last modification: %ld : %s", file_stats.st_mtime, ctime(&file_stats.st_mtime));
printf(" time of last change: %ld : %s", file_stats.st_ctime, ctime(&file_stats.st_ctime));

return 0;
}

Node, machine, version, etc.. info

#include // here include stdio.h file
#include // here include unistd.h file
#include // here include sys/utsname.h file

int main(void) {
char cmpname[256];
struct utsname uts;

if(gethostname(cmpname, 255) == 0)
printf("gethostname : %s\n", cmpname);

if(uname(&uts) == 0) {
printf("uts.sysname : %s\n", uts.sysname);
printf("uts.machine : %s\n", uts.machine);
printf("uts.nodename : %s\n", uts.nodename);
printf("uts.release : %s\n", uts.release);
printf("uts.version : %s\n", uts.version);
// GNU adds an extra extension .domainname
}

return 0;
}

Getopt example

#include // here include stdio.h file
#include // here include getopt.h file

#define PACKAGE "getoptex"
#define VERSION "0.0.1"

void print_help(int exval);

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

/*
// no arguments given
*/
if(argc == 1) {
fprintf(stderr, "This program needs arguments....\n\n");
print_help(1);
}

while((opt = getopt(argc, argv, "hVvf:o:")) != -1) {
switch(opt) {
case 'h':
print_help(0);
break;
case 'V':
printf("%s %s\n\n", PACKAGE, VERSION);
exit(0);
break;
case 'v':
printf("%s: Verbose option is set `%c'\n", PACKAGE, optopt);
break;
case 'f':
printf("%s: Filename %s\n", PACKAGE, optarg);
break;
case 'o':
printf("Output: %s\n", optarg);
break;
case ':':
fprintf(stderr, "%s: Error - Option `%c' needs a value\n\n", PACKAGE, optopt);
print_help(1);
break;
case '?':
fprintf(stderr, "%s: Error - No such option: `%c'\n\n", PACKAGE, optopt);
print_help(1);
}
}

/*
// print all remaining options
*/
for(; optind < argc; optind++)
printf("argument: %s\n", argv[optind]);

return 0;
}

void print_help(int exval) {
printf("%s,%s show working getopt example\n", PACKAGE, VERSION);
printf("%s [-h] [-V] [-f FILE] [-o FILE]\n\n", PACKAGE);

printf(" -h print this help and exit\n");
printf(" -V print version and exit\n\n");

printf(" -v set verbose flag\n");
printf(" -f FILE set intput file\n");
printf(" -o FILE set output file\n\n");

exit(exval);
}

Get parent pid program

#include // here include stdio.h file
#include // here include sys/types.h file
#include // here include unistd.h file

int main(void) {
pid_t pid;
pid = fork();

if(pid == 0) {
printf("I am child with pid: %d\n", getpid());
printf("as a child my parent pid is: %d\n", getppid());
} else {
printf("I am a parent with pid: %d\n", getpid());
printf("as a parent my child pid is: %d\n", pid);
}

/* Following code executes in both processes */
printf("oew.. I have to exit: %d\n", getpid());
exit(0);
}

Fcntl, locking files

#include // here include stdio.h file
#include // here include fcntl.h file
#include // here include stdlib.h file
#include // here include unistd.h file

#define PACKAGE "crlock"

int main(void) {
int fd = 0;
int i = 5;

for(; i > 0; i--) {
if((fd = open("locked.file", O_RDWR|O_CREAT|O_EXCL, 0444)) == -1) {
fprintf(stderr, "%s [%d]: Error - file already locked ...\n", PACKAGE, getpid());
sleep(1);
} else {
fprintf(stdout, "%s [%d]: Now I am the only one with access :-)\n",
PACKAGE, getpid());

sleep(1);
close(fd);
unlink("locked.file");
sleep(1);
} /* else */
} /* while */

return 0;
}

Create temporary file

#include // here include stdio.h file

int main(void) {
char tmpname[L_tmpnam];
char *filename = NULL;
FILE *tmpfp;

filename = tmpnam(tmpname);

printf("Temp file: %s\n", filename);

tmpfp = tmpfile();
if(tmpfp)
printf("Opened a temp file: OK\n");
else
perror("tmpfile");

return 0;
}

Create [alpha]sorted directory listing

#include // here include stdio.h file
#include // here include stdlib.h file /* free() */
#include // here include dirent.h file

int main(void) {
struct dirent **filelist = {0};
char *directory = ".";
int fcount = -1;
int i = 0;

fcount = scandir(directory, &filelist, 0, alphasort);

if(fcount < 0) {
perror(directory);
return 1;
}

for(i = 0; i < fcount; i++) {
printf("%02d: %s\n", i, filelist[i]->d_name);
free(filelist[i]);
}

free(filelist);
return 0;
}

Copy file using mmap()

#include // here include unistd.h file
#include // here include sys/mman.h file

#define PACKAGE "mmap"

int main(int argc, char *argv[]) {
int input, output;
size_t filesize;
void *source, *target;

if(argc != 3)
fprintf(stderr, "%s SOURCE DEST\n"), exit(1);

if((input = open(argv[1], O_RDONLY)) == -1)
fprintf(stderr, "%s: Error: opening file: %s\n", PACKAGE, argv[1]), exit(1);

if((output = open(argv[2], O_RDWR|O_CREAT|O_TRUNC, 0666)) == -1)
fprintf(stderr, "%s: Error: opening file: %s\n", PACKAGE, argv[2]), exit(1);

filesize = lseek(input, 0, SEEK_END);
lseek(output, filesize - 1, SEEK_SET);
write(output, '\0', 1);

if((source = mmap(0, filesize, PROT_READ, MAP_SHARED, input, 0)) == (void *) -1)
fprintf(stderr, "Error mapping input file: %s\n", argv[1]), exit(1);

if((target = mmap(0, filesize, PROT_WRITE, MAP_SHARED, output, 0)) == (void *) -1)
fprintf(stderr, "Error mapping ouput file: %s\n", argv[2]), exit(1);

memcpy(target, source, filesize);

munmap(source, filesize);
munmap(target, filesize);

close(input);
close(output);

return 0;
}

Convert unix to dos newline

#include // here include stdio.h file
#include // here include getopt.h file

#define PACKAGE "todos"
#define VERSION "0.0.1"

void print_help(int exval);
void todos(FILE *fp);

int main (int argc, char* argv[]) {
FILE *fp = stdin;
int opt = 0;

while((opt = getopt(argc, argv, "hv")) != -1) {
switch(opt) {
case 'h':
print_help(0);
break;
case 'v':
printf("%s %s\n", PACKAGE, VERSION);
exit(0);
break;
case '?':
fprintf(stderr, "%s: Error - No such option `%c'\n\n",
PACKAGE, optopt);
print_help(1);
}
}

/* no input files ... ? parse stdin() */
if((argc - optind) == 0) {
todos(fp);
} else {
for(; optind < argc; optind++) {
if(freopen(argv[optind], "r", fp) == NULL) {
fprintf(stderr, "%s: Error opening `%s'\n", PACKAGE, argv[optind]);
return 1;
}
todos(fp);
fclose(fp);
}
}

return 0;
}

void todos(FILE *fp) {
char c;

while((c = fgetc(fp)) != EOF) {
if(c == '\n')
printf("%c", '\r');

printf("%c", c);
}
}

void print_help(int exval) {
printf("%s,%s Convert unix to dos newlines\n", PACKAGE, VERSION);
printf("Usage: %s [-h] [-v] FILE...\n\n", PACKAGE);

printf(" -h print this help and exit\n");
printf(" -v print version and exit\n\n");

exit(exval);
}

Convert a UTC time value

#include // here include stdio.h file
#include // here include time.h file
#include // here include stdlib.h file

int main(int argc, char *argv[]) {
struct tm *tm_ptr;
time_t the_time;

if(argc == 2)
the_time = atoi(argv[1]);
else
(void)time(&the_time);

tm_ptr = gmtime(&the_time);

printf("raw `UTC' : %ld\n", the_time);
printf("ctime : %s", ctime(&the_time));
printf("gmtime : %02d:%02d:%02d - %02d/%02d/%02d\n",
tm_ptr->tm_hour, tm_ptr->tm_min, tm_ptr->tm_sec,
tm_ptr->tm_year - 100, tm_ptr->tm_mon + 1, tm_ptr->tm_mday);

return 0;
}

Convert a time value to and from UTC time

#include // here include stdio.h file
#include // here include getopt.h file
#include // here include string.h file
#include // here include stdlib.h file
#include // here include unistd.h file
/* strptime() */
#define __USE_XOPEN
#include // here include time.h file

#define PACKAGE "utconv"
#define VERSION "0.0.1"

void print_help(int exval); /* status epilepticus, print help */
int get_utc(char *str); /* extract UTC time from string */
char *convert_utc(int uval); /* convert UTC to time string */

int main(int argc, char *argv[]) {
int opt = 0;

if(argc == 1)
print_help(0);

while((opt = getopt(argc, argv, "hvu:s:")) != -1) {
switch(opt) {
case 'h': /* print help and exit */
print_help(0);
break;
case 'v': /* print version and exit */
fprintf(stdout, "%s %s\n", PACKAGE, VERSION);
exit(0);
break;
case 'u': /* convert INT utc value to timestring */
printf("%s\n", convert_utc(atoi(optarg)));
break;
case 's': /* convert STR to INT utc time value */
/* small check for correct user input ... */
if(strlen(optarg) < 23 || strlen(optarg) > 24) {
fprintf(stderr, "%s: Error, correct format ? `%s'\n", PACKAGE, optarg);
fprintf(stderr, "%s: Something like this maybe: `Sun Sep 7 00:00:04 2003'\n\n",
PACKAGE);
return 1;
}
printf("%d\n", get_utc(optarg));
break;
case '?':
fprintf(stderr, "%s: Error - No such option `%c'\n", PACKAGE, optopt);
print_help(1);
case ':':
fprintf(stderr, "%s: Error - Option `%c' requires an argument\n", PACKAGE, optopt);
print_help(1);
} /* switch */
} /* while */

return 0;
}

/* convert INT UTC to time string */
char *convert_utc(int uval) {
time_t timeval;
char *tstr = NULL;

timeval = uval;
tstr = strdup(ctime(&timeval));

/* remove trailing newline */
tstr[strlen(tstr) - 1] = '\0';

return tstr;
free(tstr);
}

int get_utc(char *str) {
struct tm timestruct;
int retval = 0;

/* Sun Sep 7 00:00:04 2003 */
if(strptime(str, "%a %b %d %T %Ey", ×truct) == 0)
return -1;
else {
timestruct.tm_year -= 1900;
timestruct.tm_isdst = -1;
}

retval = mktime(×truct);
return retval;
}

/* print help, status epilepticus */
void print_help(int exval) {
printf("%s,%s convert a time value to and from UTC time\n", PACKAGE, VERSION);
printf("Usage: %s [-h] [-v] [-s STR] [-u INT]\n\n", PACKAGE);

printf(" -h print this help and exit\n");
printf(" -v print version info and exit\n\n");

printf(" -u INT convert UTC time `INT' to a human readable format\n");

printf(" -s STR convert time `STRING' to an UTC value\n");
printf(" format of `STR' should be:\n");
printf(" Sun Sep 7 00:00:04 2003\n\n");

exit(exval);
}

Appending two files

#include // here include stdio.h file
#include // here include unistd.h file
#include // here include sys/types.h file
#include // here include sys/stat.h file
#include // here include fcntl.h file

int main(int argc, char **argv) {
char buf[1024];
int n, in, out;

if(argc != 3) {
fprintf(stderr, "Usage: append SOURCE TARGET\n");
return 0;
}

/* open the first file for reading */
in = open(argv[1], O_RDONLY);
/* the second file for writing */
out = open(argv[2], O_WRONLY|O_APPEND);

/* copy data from the first file to the second file */
while((n = read(in, buf, sizeof(buf))) > 0)
write(out, buf, n);

return 0;
}

Monday, April 11, 2011

A very simple shell

#include // here include stdio.h file
#include // here include sys/types.h file
#include // here include sys/wait.h file
#include // here include unistd.h file

int main(void) {
char command[BUFSIZ];
int status;
pid_t pid;

for(;;) {
printf("simpsh: ");
if(fgets(command, sizeof(command), stdin) == NULL) {
printf("\n");
return 0;
}

command[strlen(command) - 1] = '\0';
if((pid = fork()) == 0)
execlp(command, command, 0);

while(wait(&status) != pid)
continue;

printf("\n");
}
}

Sunday, April 10, 2011

PRINT PRIME NUMBERS BETWEEN 1-300 USING BREAK AND CONTINUE IN C

#include // here include math.h file
#include // here include stdio.h file
main()
{
int i, j;
i = 1;
while ( i < 300 )
{
j = 2;
while ( j < sqrt(i) )
{
if ( i % j == 0 )
break;
else
{
++j;
continue;
}
}
if ( j > sqrt(i) )
printf("%d\t", i);
++i;
}
return 0;

CHECKING LEAP YEAR USING C PROGRAM

#include // here include stdio.h file
#include // here include conio.h
void main(){
int year;
clrscr();
printf("Enter any year: ");
scanf("%d",&year);
if(((year%4==0)&&(year%100!=0))||(year%400==0))
printf("%d is a leap year",year);
else
printf("%d is not a leap year",year);
getch();
}

PRINTING ASCII VALUE USING C PROGRAM

#include // here include stdio.h file
void main(){
int i;
for(i=0;i<=255;i++){
printf("%d -> %c ",i,i);
}
return 0;
}

TO FIND FIBONACCI SERIES USING C PROGRAM

#include // here include stdio.h file
int main(){
int n,r,ncr;
printf("Enter any two numbers->");
scanf("%d %d",&n,&r);
ncr=fact(n)/(fact(r)*fact(n-r));
printf("The NCR factor of %d and %d is %d",n,r,ncr);
return 0;
}
int fact(int n){
int i=1;
while(n!=0){
i=i*n;
n--;
}
return i;
}

Write a c program to find out NCR factor of given number

#include // here include stdio.h file
int main(){
int n,r,ncr;
printf("Enter any two numbers->");
scanf("%d %d",&n,&r);
ncr=fact(n)/(fact(r)*fact(n-r));
printf("The NCR factor of %d and %d is %d",n,r,ncr);
return 0;
}
int fact(int n){
int i=1;
while(n!=0){
i=i*n;
n--;
}
return i;
}

FIND PRIME FACTORS OF A NUMBER USING C PROGRAM

#include // here include stdio.h file
int main(){
int num,i=1,j,k;
printf("\nEnter a number:");
scanf("%d",&num);
while(i<=num){
k=0;
if(num%i==0){
j=1;
while(j<=i){
if(i%j==0)
k++;
j++;
}
if(k==2)
printf("\n%d is a prime factor",i);
}
i++;
}
return 0;
}

TO FIND FACTORIAL OF A NUMBER USING C PROGRAM

#include // here include stdio.h file
int main(){
int i=1,f=1,num;
printf("\nEnter a number:");
scanf("%d",&num);
while(i<=num){
f=f*i;
i++;
}
printf("\nFactorial of %d is:%d",num,f);
return 0;
}

TO FIND MULTIPLICATION TABLE USING C PROGRAM

#include // here include stdio.h file
int main(){
int r,i,j,k;
printf("\nEnter the number range:-");
scanf("%d",&r);
for(i=1;i<=r;i++){
for(j=1;j<=10;j++)
printf(" %d*%d=%d",i,j,i*j);
printf("\n");
}
return 0;
}

Write a c program to print Pascal triangle

#include // here include stdio.h file
int main(){
int line,i,j,k;
printf("Enter the no. of lines");
scanf("%d",&line);
for(i=1;i<=line;i++){
for(j=1;j<=line-i;j++)
printf(" ");
for(k=1;k printf("%d",k);
for(k=i;k>=1;k--)
printf("%d",k);
printf("\n");
}
return 0;
}

Write a c program for Floyd’s triangle.

#include // here include stdio.h file
void main(){
int i,j,r,k=1;
printf("\nEnter the range:");
scanf("%d",&r);
printf("\nFLOYD'S TRIANGLE\n\n");
for(i=1;i<=r;i++){
for(j=1;j<=i;j++,k++)
printf(" %d",k);
printf("\n");
}
return 0;
}

Write a c program which passes two dimension array to function

#include // here include stdio.h file
#define M 3
#define N 5
void fstore2D(int a[][N]);
void fretrieve2D(int a[][N]);
int main(){
int a[M][N];
printf("Input data in matrix (%d X %d)\n", M, N);
fstore2D(a);
fretrieve2D(a);
return 0;
}
void fstore2D(int a[][N]){
int i, j;
for (i = 0; i < M; ++i){
for (j = 0; j < N; ++j)
scanf("%d", &a[i][j]);
}
}
void fretrieve2D(int a[][N]){
int i, j;
for ( i = 0; i < M; ++i ){
for ( j = 0; j < N; ++j)
printf("%6d ", a[i][j]);
printf("\n");
}
}

How to pass one dimensional array to function in c

#include // here include stdio.h file
#define N 5
void fstore1D(int a[], int a_size);
void fretrieve1D(int a[], int a_size);
void fedit1D(int a[], int a_size);
int main(){
int a[N];
printf("Input data into the matrix:\n");
fstore1D(a, N);
fretrieve1D(a, N);
fedit1D(a, N);
fretrieve1D(a, N);
return 0;
}

void fstore1D(int a[], int n){
int i;
for ( i = 0; i < n; ++i )
scanf("%d", &a[i]);
}

void fretrieve1D(int a[], int n){
int i;
for ( i = 0; i < n; ++i )
printf("%6d ", a[i]);
printf("\n");
}

void fedit1D(int a[], int n){
int i, q;
for ( i = 0; i < n; ++i ){
printf("Prev. data: %d\nEnter 1 to edit 0 to skip.", a[i]);
scanf("%d", &q);
if ( q == 1 ){
printf("Enter new value: ");
scanf("%d", &a[i]);
}
}
}

FIND OUT GENERIC ROOT OF A NUMBER By C PROGRAM

#include // here include stdio.h file
int main(){
long int num,sum,r;
printf("\nEnter a number:-");
scanf("%ld",&num);
while(num>10){
sum=0;
while(num){
r=num%10;
num=num/10;
sum+=r;
}
if(sum>10)
num=sum;
else
break;
}
printf("\nSum of the digits in single digit is: %ld",sum);
return 0;
}

Write a c program to find largest among three numbers using conditional operator

#include // here include stdio.h file
int main(){
int a,b,c,big;
printf("\nEnter 3 numbers:");
scanf("%d %d %d",&a,&b,&c);
big=(a>b&&a>c?a:b>c?b:c);
printf("\nThe biggest number is:%d",big);
return 0;
}

Write a c program to find largest among three numbers using binary minus operator

#include // here include stdio.h file
int main(){
int a,b,c;
printf("\nEnter 3 numbers: ");
scanf("%d %d %d",&a,&b,&c);
if(a-b>0 && a-c>0)
printf("\nGreatest is a :%d",a);
else
if(b-c>0)
printf("\nGreatest is b :%d",b);
else
printf("\nGreatest is c :%d",c);
return 0;
}

FIND POWER OF A NUMBER USING C PROGRAM

#include // here include stdio.h file
int main(){
int pow,num,i=1;
long int sum=1;
printf("\nEnter a number: ");
scanf("%d",&num);
printf("\nEnter power: ");
scanf("%d",&pow);
while(i<=pow){
sum=sum*num;
i++;
}
printf("\n%d to the power %d is: %ld",num,pow,sum);
return 0;
}

Write a c program to check given string is palindrome number or not

#include // here include string.h file
#include // here include stdio.h file
int main(){
char *str,*rev;
int i,j;
printf("\nEnter a string:");
scanf("%s",str);
for(i=strlen(str)-1,j=0;i>=0;i--,j++)
rev[j]=str[i];
rev[j]='\0';
if(strcmp(rev,str))
printf("\nThe string is not a palindrome");
else
printf("\nThe string is a palindrome");
return 0;
}

check the given number is palindrome number or not using c program

#include // here include stdio.h file
int main(){
int num,r,sum=0,temp;
printf("\nEnter a number:");
scanf("%d",&num);
temp=num;
while(num){
r=num%10;
num=num/10;
sum=sum*10+r;
}
if(temp==sum)
printf("\n%d is a palindrome",temp);
else
printf("\n%d is not a palindrome",temp);
return 0;
}

Write a c program to find out sum of digit of given number

#include // here include stdio.h file
int main(){
int num,sum=0,r;
printf("\nEnter a number:");
scanf("%d",&num);
while(num){
r=num%10;
num=num/10;
sum=sum+r;
}
printf("sum=%d",sum);
return 0;
}

Write a c program to check given number is strong number or not

Write a c program to check given number is strong number or not


#include // here include stdio.h file
int main(){
int num,i,f,r,sum=0,temp;
printf("\nEnter a number");
scanf("%d",&num);
temp=num;
while(num){
i=1,f=1;
r=num%10;
while(i<=r){
f=f*i;
i++;
}
sum=sum+f;
num=num/10;
}
if(sum==temp)
printf("%d is a strong number",temp);
else
printf("%d is not a strong number",temp);
return 0;
}

reverse any number using c program

reverse any number using c program


#include // here include stdio.h file
int main(){
int num,out;
scanf("%d",&num);
out=rev(num);
printf("%d",out);
return 0;
}

int rev(int num){
static sum,r;
if(num){
r=num%10;
sum=sum*10+r;
rev(num/10);
}
else return 0;
return sum;
}

check given number is prime number or not using c program

check given number is prime number or not using c program


#include // here include stdio.h file
int main(){
int num,i,count=0;
printf("\nEnter a number:");
scanf("%d",&num);
for(i=2;i<=num/2;i++){
if(num%i==0){
count++;
break;
}
}
if(count==0)
printf("%d is a prime number",num);
else
printf("%d is not a prime number",num);
return 0;
}

Check the given number is armstrong number or not using c program

Check the given number is armstrong number or not using c program


#include // here include stdio.h file
int main(){
int num,r,sum=0,temp;
printf("\nEnter a number:-");
scanf("%d",&num);
temp=num;
while(num!=0){
r=num%10;
num=num/10;
sum=sum+(r*r*r);
}
if(sum==temp)
printf("\nThe number %d is an armstrong number",temp);
else
printf("\nThe number %d is not an armstrong number",temp);
return 0;
}

Find out the perfect number using c program

Find out the perfect number using c program

#include // here include stdio.h file
int main(){
int n,i=1,sum=0;
printf("\nEnter a number:-");
scanf("%d",&n);
while(i < n)
{
if(n%i==0)
sum=sum+i;
i++;
}
if(sum==n)
printf("\nThe no %d is a perfect number",i);
else
printf("\nThe no %d is not a perfect number",i);
return 0;
}

Gesture detection in Android Part - 1

Gesture detection is one of the great features of all touch based mobile devices. Gestures are patterns drawn by the user on the screen. Simple gestures include tap, scroll, swipe, etc. Complex gestures are more complex patterns drawn on the screen. In Android we can detect simple gestures using GestureDetector class and complex gestures using GestureOverlayView class.

GestureDetector is a class which is used to detect simple gestures like tap, scroll, swipe or fling, etc. This class detects gestures using the supplied MotionEvent class. We use this class along with the onTouchEvent, inside this method we call the GestureDetector.onTouchEvent. GestureDetector identify the gestures or events that occurred and report back to us using GestureDetector.OnGestureListener callback interface. We create an instance of the GestureDetector class by passing Context and GestureDetector.OnGestureListener listener.

The GestureDetector.OnGestureListener interface has following abstract methods:

abstract boolean onDown(MotionEvent e)
abstract void onLongPress(MotionEvent e)
abstract boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
abstract void onShowPress(MotionEvent e)
abstract boolean onSingleTapUp(MotionEvent e)
abstract boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)

The onDown method is called when the user first touch the screen, the MotionEvent parameter represents the event that corresponds to the touch event.

The onLongPress method is called when user touches the screen and holds it for a period of time. The MotionEvent parameter represents the event that corresponds to the touch event.

The onScroll method is called when the user touches the screen and moves to another location on the screen. This method has 4 parameters; first MotionEvent corresponds to the first touch event that occurred, second MotionEvent corresponds to the scroll that occurred, the distanceX parameter represents the scrolled distance along the X axis since the last call to onScroll and the forth parameter distanceY is the distance occurred along Y axis since the last call to onScroll. The third and forth parameters are little bit confusing and are not the distance between MotionEvent 1 and MotionEvent 2.

The onShowPress method is called when the user touches the phone and not moved yet. This event is mostly used for giving visual feedback to the user to show their action.

The onSingleTapUp method is called when a tap occurred, i.e. use taps the screen.

The onFling method is called whenever the user swipes the screen in any direction, i.e. the user touches the screen and immediately moves the finger in any direction. The first parameter is the MotionEvent corresponds to the touch event that started the fling, second parameter is the MotionEvent that corresponds to the movement that triggered the fling, the third one corresponds to the velocity along X axis measured and the forth one corresponds to the velocity along Y axis measured. The use of this gesture depends on application to application. Some application starts the movement of some objects in the screens with velocity based on the X and Y velocity measured and gradually slows down the movement and settled the objects somewhere on the screen. Another use of this method is to move from one page to another within the application.

Double-tap :-

You should be noticed that the double-tap event is not present in the GestureDetector.onGestureListener callback interface. For some reason this event is reported using another callback interface GestureDetector.onDoubleTapListener. To use this callback interface we have to register for these events using GestureDetector.setOnDoubleTapListener passing the above listener. This interface has the following methods:

abstract boolean onDoubleTap(MotionEvent e)
abstract boolean onDoubleTapEvent(MotionEvent e)
abstract boolean onSingleTapConfirmed(MotionEvent e)

The onDoubleTap method is called when there is a double-tap event occurred. The only parameter MotionEvent corresponds to the double-tap event that occurred.

The onDoubleTapEvent is called for all events that occurred within the double-tap, i.e. down, move and up events.

The onSingleTapConfirmed method is called when there is a single tap occurred and confirmed, but this is not same as the single-tap event in the GestureDetector.onGestureListener. This is called when the GestureDetector detects and confirms that this tap does not lead to a double-tap.

The MotionEvent class

The MotionEvent class contains all the values correspond to a movement and touch event. This class holds values such as X and Y position at which the event occurred, timestamp at which the event occurred, mouse pointer index, etc. This class also contains the multi-touch information. Another interesting member is the pressure variable, which reports the pressure of the touch and movement events. I am experimenting with multi-touch and pressure and will be posting an article soon.

Example application:-

The example application accompanies this article is a simple one to show the use of these gestures. The application has 4 views and each view has different color. It has and 2 modes, SCROLL mode and FLIP mode. The application starts in FLIP mode. In this mode when you perform the swipe/fling gesture in left right, up and down direction, the view changes back and forth. When a long-press is detected, the application changes to SCROLL mode, in this mode you scroll the displayed view. While in this mode, you can double-tap on the screen to bring back the screen to its original position. Again when a long-press is detected the application changes to FLIP mode.

FlipperActivity.java :-

package com.raghu.samples.gesturedetectorsample;
import java.util.ArrayList;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.OvershootInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.TextView;
import android.widget.ViewFlipper;

public class FlipperActivity extends Activity implements GestureDetector.OnGestureListener,GestureDetector.OnDoubleTapListener{

final private int SWIPE_MIN_DISTANCE = 100;
final private int SWIPE_MIN_VELOCITY = 100;
private ViewFlipper flipper = null;
private ArrayList views = null;
private GestureDetector gesturedetector = null;
private Vibrator vibrator = null;
int colors[] = { Color.rgb(255,128,128), Color.rgb(128,255,128),
Color.rgb(128,128,255), Color.rgb(128,128,128) };

private Animation animleftin = null;
private Animation animleftout = null;
private Animation animrightin = null;
private Animation animrightout = null;
private Animation animupin = null;
private Animation animupout = null;
private Animation animdownin = null;
private Animation animdownout = null;
private boolean isDragMode = false;
private int currentview = 0;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

flipper = new ViewFlipper(this);
gesturedetector = new GestureDetector(this, this);
vibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE);
gesturedetector.setOnDoubleTapListener(this);
flipper.setInAnimation(animleftin);
flipper.setOutAnimation(animleftout);
flipper.setFlipInterval(3000);
flipper.setAnimateFirstView(true);
prepareAnimations();
prepareViews();
addViews();
setViewText();

setContentView(flipper);
}

private void prepareAnimations() {
animleftin = new TranslateAnimation(
Animation.RELATIVE_TO_PARENT, +1.0f, Animation.RELATIVE_TO_PARENT, 0.0f,
Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f);

animleftout = new TranslateAnimation(
Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, -1.0f,
Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f);

animrightin = new TranslateAnimation(
Animation.RELATIVE_TO_PARENT, -1.0f, Animation.RELATIVE_TO_PARENT, 0.0f,
Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f);

animrightout = new TranslateAnimation(
Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, +1.0f,
Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f);

animupin = new TranslateAnimation(
Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f,
Animation.RELATIVE_TO_PARENT, +1.0f, Animation.RELATIVE_TO_PARENT, 0.0f);

animupout = new TranslateAnimation(
Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f,
Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, -1.0f);

animdownin = new TranslateAnimation(
Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f,
Animation.RELATIVE_TO_PARENT, -1.0f, Animation.RELATIVE_TO_PARENT, 0.0f);

animdownout = new TranslateAnimation(
Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f,
Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, +1.0f);

animleftin.setDuration(1000);
animleftin.setInterpolator(new OvershootInterpolator());
animleftout.setDuration(1000);
animleftout.setInterpolator(new OvershootInterpolator());
animrightin.setDuration(1000);
animrightin.setInterpolator(new OvershootInterpolator());
animrightout.setDuration(1000);
animrightout.setInterpolator(new OvershootInterpolator());
animupin.setDuration(1000);
animupin.setInterpolator(new OvershootInterpolator());
animupout.setDuration(1000);
animupout.setInterpolator(new OvershootInterpolator());
animdownin.setDuration(1000);
animdownin.setInterpolator(new OvershootInterpolator());
animdownout.setDuration(1000);
animdownout.setInterpolator(new OvershootInterpolator());
}

private void prepareViews(){
TextView view = null;

views = new ArrayList();

for(int color: colors)
{
view = new TextView(this);

view.setBackgroundColor(color);
view.setTextColor(Color.BLACK);
view.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);

views.add(view);
}
}

private void addViews(){
for(int index=0; index {
flipper.addView(views.get(index),index,
new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
}
}

private void setViewText(){
String text = getString(isDragMode ? R.string.app_info_drag : R.string.app_info_flip);
for(int index=0; index {
views.get(index).setText(text);
}
}

@Override
public boolean onTouchEvent(MotionEvent event) {
return gesturedetector.onTouchEvent(event);
}

@Override
public boolean onDown(MotionEvent e) {
return false;
}

@Override
public boolean onFling(MotionEvent event1, MotionEvent event2, float velocityX,float velocityY) {
if(isDragMode)
return false;

final float ev1x = event1.getX();
final float ev1y = event1.getY();
final float ev2x = event2.getX();
final float ev2y = event2.getY();
final float xdiff = Math.abs(ev1x - ev2x);
final float ydiff = Math.abs(ev1y - ev2y);
final float xvelocity = Math.abs(velocityX);
final float yvelocity = Math.abs(velocityY);

if(xvelocity > this.SWIPE_MIN_VELOCITY && xdiff > this.SWIPE_MIN_DISTANCE)
{
if(ev1x > ev2x) //Swipe Left
{
--currentview;

if(currentview < 0)
{
currentview = views.size() - 1;
}

flipper.setInAnimation(animleftin);
flipper.setOutAnimation(animleftout);
}
else //Swipe Right
{
++currentview;

if(currentview >= views.size())
{
currentview = 0;
}

flipper.setInAnimation(animrightin);
flipper.setOutAnimation(animrightout);
}

flipper.scrollTo(0,0);
flipper.setDisplayedChild(currentview);
}
else if(yvelocity > this.SWIPE_MIN_VELOCITY && ydiff > this.SWIPE_MIN_DISTANCE)
{
if(ev1y > ev2y) //Swipe Up
{
--currentview;

if(currentview < 0)
{
currentview = views.size() - 1;
}

flipper.setInAnimation(animupin);
flipper.setOutAnimation(animupout);
}
else //Swipe Down
{
++currentview;

if(currentview >= views.size())
{
currentview = 0;
}
flipper.setInAnimation(animdownin);
flipper.setOutAnimation(animdownout);
}

flipper.scrollTo(0,0);
flipper.setDisplayedChild(currentview);
}

return false;
}

@Override
public void onLongPress(MotionEvent e) {
vibrator.vibrate(200);
flipper.scrollTo(0,0);

isDragMode = !isDragMode;

setViewText();
}

@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,float distanceY) {
if(isDragMode)
flipper.scrollBy((int)distanceX, (int)distanceY);

return false;
}

@Override
public void onShowPress(MotionEvent e) {
}

@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}

@Override
public boolean onDoubleTap(MotionEvent e) {
flipper.scrollTo(0,0);

return false;
}

@Override
public boolean onDoubleTapEvent(MotionEvent e) {
return false;
}

@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
return false;
}
}


Multi-touch in Android

Multi-touch is the ability to detect touch events with 2 or more fingers. Android supports multi-touch from version 2.0 onwards. Most common multi-touch gesture is pinch zoom. With Pinch zoom, you can zoom in or out the content by squeezing or pull apart the fingers. We can implement multi-touch in Android using either onTouch events or ScaleGestureDetector.

To View.onTouchEvent is called when we touch the screen. This method has one MotionEvent parameter. This represents the touch event that occurred. TheMotionEvent.getAction() method returns the event action. There are different event actions likeACTION_DOWN, ACTION_MOVE, ACTION_UP, ACTION_POINTER_DOWN, ACTION_POINTER_UP, etc. MotionEvent.getX() and MotionEvent.getY() returns x and y position of the event respectively.

ACTION_TOUCH will be generated whenever we touch the screen with one finger (primary pointer). ACTION_UP is generated when the finger has left the screen. This is for single touch. When we touch the screen with two fingers, the first touch detected is considered as the primary pointer and all others are considered as non-primary pointer. For the primary pointer (first touch detected) ACTION_TOUCH is generated and for the non-primary pointers (second touch onwards) ACTION_POINTER_DOWN is generated. When we move the fingers ACTION_MOVE will be generated. When the non-primary pointer left the screen, ACTION_POINTER_UP is generated.
To find now many pointers are there for an event, we can use MotionEvent.getPointerCount()method. This will return how many pointers are there for the event. The getX() and getY() methods has another variant which accepts a pointer id, i.e. MotionEvent.getX(pointerid) andMotionEvent.getY(pointerid) which returns the X and Y coordinates of the pointer with given pointerid. Note that we are passing pointer id not pointer index. The methodMotionEvent.getPointerId(index) returns the pointer id of the pointer at the specified index. The index ranges from 0 to getPointerCount() – 1. Now we have X and Y coordinates of the different pointers involved in the multi-touch gesture and we can use this to implement actions like zoom-in, zoom-out, etc.

Using ScaleGestureDetector

ScaleGestureDetector class detects gestures with more than two fingers. We use this class the same way we use the GestureDetector class, i.e. we create and instance of the class and onView.onTouchEvent we call the ScaleGestureDetector.onTouchEvent method. The ScaleGestureDetector uses callback interface ScaleGestureDetector.OnScaleGestureListener to report the events occurred. This interface has following three methods:

boolean onScaleBegin(ScaleGestureDetector detector)
boolean onScale(ScaleGestureDetector detector)
void onScaleEnd(ScaleGestureDetector detector)

The onScaleBegin method is called when two-finger gesture is detected. We have to return true to indicate we have handled this event and all the other methods should be called. If we return false then the ScaleGestureDetector will not call other methods.

The onScale method is called when we move the fingers. Note that this event will not be called when you return false from onScaleBegin callback method.

The onScaleEnd is called when the gesture is finished, i.e. then the fingers left the screen.

All these methods have one parameter ScaleGestureDetector which is instance of the ScaleGestureDetector reported the event.

The ScaleGestureDetector has different methods like, getCurrentSpan(), getFocusX(), getFocusY(), etc. The getCurrentSpan() method returns the current distance between the fingers. The getFocusX() and getFocusY() methods returns the focal point’s (middle point) X and Y coordinates respectively. Using this information we can implement the pinch-zoom gesture.

Sample Application

The sample application is a simple one which draws a line between different pointers when you touch the screen with two fingers. The pinch-zoom is not implemented in this application but can be done with minimal effort.

Please use below code as per Andriod standards.Create one folder in src folder like

" /src/com/raghu/samples/multitouchsample/AppLog.java"
" /src/com/raghu/samples/multitouchsample/MainActivity.java"
" /src/com/raghu/samples/multitouchsample/MultitouchView.java"

Please check below code for above application :

AppLog.java :-

package com.raghu.samples.multitouchsample;
import android.util.Log;

public class AppLog {
private final static String APP_TAG = "com.raghu.samples.multitouchsample";

public static int log(String message){
return Log.i(APP_TAG,message);
}
}

MainActivity.java :-

package com.raghu.samples.multitouchsample;
import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}


MultitouchView.java :-

package com.raghu.samples.multitouchsample;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.PointF;
import android.util.AttributeSet;
//import android.util.FloatMath;
import android.view.MotionEvent;
import android.view.View;

public class MultitouchView extends View {
private static final int STROKE_WIDTH = 1;
private static final int CIRCLE_RADIUS = 20;

private ArrayList touchPoints = null;
private Paint drawingPaint = null;
private boolean isMultiTouch = false;
private int pathEffectPhase = 0;

public MultitouchView(Context context) {
super(context);

initialize(context);
}

public MultitouchView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initialize(context);
}

public MultitouchView(Context context, AttributeSet attrs) {
super(context, attrs);
initialize(context);
}

@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if(touchPoints.size() > 0)
{
DashPathEffect effect = new DashPathEffect(new float[] {7,7}, pathEffectPhase);
PointF midpt = null;
drawingPaint.setPathEffect(effect);
for(int index=1; index {
midpt = getMidPoint(
touchPoints.get(index - 1).x,touchPoints.get(index - 1).y,
touchPoints.get(index).x,touchPoints.get(index).y);

canvas.drawCircle(
touchPoints.get(index - 1).x,touchPoints.get(index - 1).y,
1, drawingPaint);
canvas.drawCircle(
touchPoints.get(index - 1).x,touchPoints.get(index - 1).y,
CIRCLE_RADIUS, drawingPaint);

canvas.drawCircle(touchPoints.get(index).x,touchPoints.get(index).y,
1, drawingPaint);
canvas.drawCircle(touchPoints.get(index).x,touchPoints.get(index).y,
CIRCLE_RADIUS, drawingPaint);

canvas.drawLine(
touchPoints.get(index - 1).x,touchPoints.get(index - 1).y,
touchPoints.get(index).x,touchPoints.get(index).y,
drawingPaint);

canvas.drawCircle(midpt.x,midpt.y, 10, drawingPaint);
}

++pathEffectPhase;

invalidate();
}
}

@Override
public boolean onTouchEvent(MotionEvent event) {
super.onTouchEvent(event);
int action = event.getAction() & MotionEvent.ACTION_MASK;
switch(action)
{
case MotionEvent.ACTION_DOWN:
{
invalidate();
break;
}
case MotionEvent.ACTION_POINTER_DOWN:
{
isMultiTouch = true;

setPoints(event);
invalidate();

break;
}
case MotionEvent.ACTION_POINTER_UP:
{
isMultiTouch = false;
break;
}
case MotionEvent.ACTION_MOVE:
{
if(isMultiTouch)
{
setPoints(event);
invalidate();
}

break;
}
}

return true;
}

private void initialize(Context context){
drawingPaint = new Paint();
drawingPaint.setColor(Color.RED);
drawingPaint.setStrokeWidth(STROKE_WIDTH);
drawingPaint.setStyle(Paint.Style.STROKE);
drawingPaint.setAntiAlias(true);
touchPoints = new ArrayList();
}

public void setPoints(MotionEvent event){
touchPoints.clear();
int pointerIndex = 0;
for(int index=0; index {
pointerIndex = event.getPointerId(index);
touchPoints.add(new PointF(event.getX(pointerIndex),event.getY(pointerIndex)));
}
}

private PointF getMidPoint(float x1,float y1, float x2, float y2) {
PointF point = new PointF();
float x = x1 + x2;
float y = y1 + y2;
point.set(x / 2, y / 2);
return point;
}
}


For MotionEvent Documentation


Saturday, April 9, 2011

Using hardware sensors in Android part-1

Hardware sensors are present in almost all the modern mobile phone devices. Different types of sensors like accelerometer sensor, magnetic field sensor, orientation sensor, proximity sensor, etc. are present in these devices. Sensors that are present vary from device to device.
In Android different types of sensors are supported. SensorManager class is used to access these sensors. Sensor Manager is a system service running in Android. We get an instance of this service by calling Context.getSystemService() method with SENSOR_MANAGER as the argument. Android supports different types of sensors, some of them are:

Sensor.TYPE_ACCELEROMETER - accelerometer sensor
Sensor.TYPE_GYROSCOPE - gyroscope sensor
Sensor.TYPE_LIGHT - light sensor
Sensor.TYPE_MAGNETIC_FIELD - magnetic field sensor
Sensor.TYPE_ORIENTATION - orientation sensor
Sensor.TYPE_PRESSURE - pressure sensor
Sensor.TYPE_PROXIMITY - proximity sensor
Sensor.TYPE_TEMPERATURE - temperature sensor

Not all these will present in the target device, so before start using a particular type of sensor, we need to check whether the desired sensor is present in the device or not. We can check the presence using either SensorManager.getDefaultSensor() or ServiceManager.getSensorList(). Both methods accept sensor type parameter as an argument. In case of ServiceManager.getSensorList() method we can pass the Sensor. TYPE_ALL to get all the sensors present in the system. Once we confirm the desired sensor is present in the device, we can start getting the event updates from the sensor using SensorManager.registerListener() method. This method accepts one SensorEventListener callback interface. This is the interface that SensorManager uses to report the calling application whenever a sensor event occurred. This callback interface has following methods:

abstract void onAccuracyChanged(Sensor sensor, int accuracy)
abstract void onSensorChanged(SensorEvent event)

The onAccuractChanged method is called when there is a change in the sensor accuracy. First parameter is the Sensor registered and second one is the accuracy value. This can be one of the following:

SensorManager.SENSOR_STATUS_ACCURACY_HIGH - high accuracy
SensorManager.SENSOR_STATUS_ACCURACY_MEDIUM - medium accuracy
SensorManager.SENSOR_STATUS_ACCURACY_LOW - low accuracy
SensorManager.SENSOR_STATUS_UNRELIABLE - accuracy is unreliable and cannot be trusted

The onSensorChanged is called when the sensor values are changed. The only argument SensorEvent is the sensor event occurred. This class holds the sensor values, accuracy of the sensor values, Sensor itself and a timestamp at which the event occurred.

SensorEvent.values contains the sensor values. This is an array of float values representing the sensor values. The length and content of this array depends on the type of sensor used. For example if the sensor is an accelerometer then it will be having three elements representing Azimuth angle, Pitch and Roll. Other sensors have different values. Sensor values are described in this link.

Sample application

Sample application for this article lists all the sensors present in the device and when you select a particular sensor, the application registers for sensor events and update the values on the screen. This application does not do anything with the values but just prints it on the screen. A real application should use these values to do something more meaning such as drawing a compass, counting steps while walking, etc.

Please use below code as per Andriod standards.Create two folders in src folder like

" /src/com/raghu/samples/sensorsample/app/AppLog.java"
" /src/com/raghu/samples/sensorsample/app/SensorSampleApp.java"
" /src/com/raghu/samples/sensorsample/ui/SensorList.java"
" /src/com/raghu/samples/sensorsample/ui/SensorTestActivity.java"

Please check below code for above application :

AppLog.java :-

package com.varma.samples.sensorsample.app;
import android.util.Log;
public class AppLog {
public static void log(String message){
Log.i("SensorList",message);
}
}

SensorSampleApp.java :-

package com.raghu.samples.sensorsample.app;
import java.util.List;
import android.app.Application;
import android.content.res.Configuration;
import android.hardware.Sensor;
import android.hardware.SensorManager;

public class SensorSampleApp extends Application{
public static final String SENSOR_INDEX = "sensorsample.sensor_index";

SensorManager manager = null;
List sensors = null;

public SensorManager getSensorManager() {
return manager;
}
public List getSensorList() {
return sensors;
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
@Override
public void onCreate() {
super.onCreate();

manager = (SensorManager)getSystemService(SENSOR_SERVICE);
sensors = manager.getSensorList(Sensor.TYPE_ALL);
}
@Override
public void onLowMemory() {
super.onLowMemory();
}
@Override
public void onTerminate() {
super.onTerminate();
}
}

SensorList.java :-

package com.raghu.samples.sensorsample.ui;
import java.util.List;
import com.raghu.samples.sensorsample.app.AppLog;
import com.raghu.samples.sensorsample.app.R;
import com.raghu.samples.sensorsample.app.SensorSampleApp;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class SensorList extends ListActivity {
SensorListAdapter adapter = null;
SensorSampleApp app = null;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
app = (SensorSampleApp)getApplication();
adapter = new SensorListAdapter(this, R.layout.listitem, app.getSensorList());

setListAdapter(adapter);
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);

AppLog.log(app.getSensorList().get(position).getName());

startSensorTestActivity(position);
}

private void startSensorTestActivity(int position) {
Intent intent = new Intent(this, SensorTestActivity.class);
intent.putExtra(SensorSampleApp.SENSOR_INDEX, position);
startActivity(intent);
}

private class SensorListAdapter extends ArrayAdapter{
private List objects = null;
public SensorListAdapter(Context context, int textviewid, List objects) {
super(context, textviewid, objects);
this.objects = objects;
}

@Override
public int getCount() {
return ((null != objects) ? objects.size() : 0);
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public Sensor getItem(int position) {
return ((null != objects) ? objects.get(position) : null);
}

public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(null == view)
{
LayoutInflater vi = (LayoutInflater)SensorList.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.listitem, null);
}

Sensor sensor = objects.get(position);
if(null != sensor)
{
TextView txtName = (TextView)view.findViewById(R.id.txtName);
TextView txtVendor = (TextView)view.findViewById(R.id.txtVendor);
TextView txtVersion = (TextView)view.findViewById(R.id.txtVersion);

txtName.setText(sensor.getName());
txtVendor.setText("Vendor: " + sensor.getVendor());
txtVersion.setText("Version: " + sensor.getVersion());
}

return view;
}
}
}

SensorTestActivity.java :-

package com.raghu.samples.sensorsample.ui;
import com.raghu.samples.sensorsample.app.AppLog;
import com.raghu.samples.sensorsample.app.R;
import com.raghu.samples.sensorsample.app.SensorSampleApp;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;

public class SensorTestActivity extends Activity implements SensorEventListener{
SensorSampleApp app = null;
int sensorIndex = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sensortest);

app = (SensorSampleApp)getApplication();
sensorIndex = getIntent().getIntExtra(SensorSampleApp.SENSOR_INDEX, 0);

String name = ((SensorSampleApp)getApplication()).getSensorList().get(sensorIndex).getName();

setTextViewText(R.id.txtSensorName, "Testing sensor using:\n" + name);
}

@Override
protected void onStop() {
AppLog.log("Unregistering event listener");

app.getSensorManager().unregisterListener(this);

super.onStop();
}

@Override
protected void onResume() {
super.onResume();

AppLog.log("Registering event listener");

app.getSensorManager().registerListener(this,
app.getSensorList().get(sensorIndex), SensorManager.SENSOR_DELAY_UI);
}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
setTextViewText(R.id.txtSensorAccuracy,"Sensor Accuracy " + getSensorAccuracyString(accuracy));
}

@Override
public void onSensorChanged(SensorEvent event) {
String sensorValues = "Sensor timestamp: " + event.timestamp + "\n\n";

for(int index=0; index sensorValues += ("Sensor Value #" + (index + 1) + ": " + event.values[index] + "\n");
}

setTextViewText(R.id.txtSensorValues,sensorValues);
}

private void setTextViewText(int id,String text){
((TextView)findViewById(id)).setText(text);
}

private String getSensorAccuracyString(int accuracy) {
String accuracyString = "Unknown";

switch(accuracy)
{
case SensorManager.SENSOR_STATUS_ACCURACY_HIGH: accuracyString = "High"; break;
case SensorManager.SENSOR_STATUS_ACCURACY_LOW: accuracyString = "Low"; break;
case SensorManager.SENSOR_STATUS_ACCURACY_MEDIUM: accuracyString = "Medium"; break;
case SensorManager.SENSOR_STATUS_UNRELIABLE: accuracyString = "Unreliable"; break;
default: accuracyString = "Unknown"; break;
}

return accuracyString;
}
}

 
# #