To find the number of the current VC, use the VT_GETSTATE ioctl, which takes a pointer to a struct vt_stat and returns the number of the current VC in the v_active element:
unsigned short get_current_vc(int fd) { struct vt_stat vs; ioctl(fd, VT_GETSTATE, &vs); return (vs.v_active); }
To locate the correct device entry for the current VC, use
sprintf(ttyname, "/dev/tty%d", get_current_vc(fd));