Labels

.NET Job Questions About Java Absract class Abstract class Abstract Class and Interface Aggregation ajax aop apache ofbiz Apache ofbiz tutrial Association authentication autocad basics batch Binary Tree bootstrap loader in java build Builder design pattern C++ Job Questions caching CallableStatement in java certifications Chain of responsibility Design pattern charts check parentheses in a string Classes classloader in java classloading concept code quality collage level java program Composition concurrency Concurrency Tutorial Converting InputStream to String Core Java core java concept core java interview questions Core Java Interview Questions Core Java Questions core java tutorial CyclicBarrier in Java data structures database Database Job Questions datetime in c# DB Db2 SQL Replication deserialization in java Design Patterns designpatterns Downloads dtd Eclipse ejb example/sample code exception handling in core java file handling injava File I/O vs Memory-Mapped Filter first program in spring flex Garbage Collection Generics concept in java grails groovy and grails Guice Heap hibernate Hibernate Interview Questions how-to IBM DB2 IBM DB2 Tutorial ide immutable Interceptor Interface interview Interview Questions for Advanced JAVA investment bank j2ee java JAVA Code Examples Java 7 java changes java class loading JAVA Classes and Objects Java Classloader concept Java classloading concept java cloning concept java collection Java collection interview questions Java Collections java concurrency Java CountDownLatch java definiton Java design pattern Java EE 5 Java EE 6 Java Exceptions Java file Java Garbage Collection Java generics Java Glossary java hot concept java immutable concept Java Interface Java interview Question java interview question 2012 java interview question answer Java Interview Questions Java Interview Questions and Answers java interview topic java investment bank Java Job Questions java multithreading java multithreading concept java new features Java Packages java proxy object java questions Java Serialization Java serialization concept java serialization interview question java session concept java string Java Swings Questions java synchronization java threading Java Threads Questions java tutorial java util; java collections; java questions java volatile java volatile interview question Java Wrapper Classes java.java1.5 java.lang.ClassCastException JavaNotes javascript JAX-WS jdbc JDBC JDBC Database connection jdk 1.5 features JDK 1.5 new features Concurrent HashMap JMS interview question JMS tutorial job JSESSIONID concept JSESSIONID interview Question JSF jsp JSP Interview Question JSP taglib JSTL with JSP Junit Junit Concept Junit interview question.Best Practices to write JUnit test cases in Java JVM Linux - Unix tutorial Marker Interfaces MD5 encryption and decryption messaging MNC software java interview question musix NCR java interview question Networking Job Questions news Object Serialization Objects ojdbc14.jar OOP Oracle Oracle SQL Query for two timestamp difference orm own JavaScript function call in Apache ofbiz Packages Palm Apps patterns pdf persistence Portal Portlet Spring Integration Prime number test in java programs Rails Reboot remote computers REST Ruby Sample application schema SCJP security Senior java developer interviews servlet3 servlets session tracking singleton design pattern Spring Spring 2.5 Framework spring ebook Spring framework concept spring MVC spring pdf Spring Security Spring Security interview questions SQL SQL performance SQL Query to create xml file Sql Query tuning ssis and ssrs StAX and XML string concept string immutable string in java strings struts Struts2 Struts2 integration synchronization works in java Technical Interview testing tips Tomcat top Tutorial Volatile in deep Volatile working concept web Web Developer Job Questions web services weblogic Weblogic Application Server websphere what is JSESSIONID xml XML parsing in java XML with Java xslt


Saturday, 6 July 2013

Data Files - C Interview Questions III


Q. How do you sort filenames in a directory?
When you are sorting the filenames in a directory, the one-at-a-time approach does not work. You need some way to store the filenames and then sort them when all filenames have been obtained. This task can be accomplished by creating an array of pointers to find_t structures for each filename that is found. As each filename is found in the directory, memory is allocated to hold the find_t entry for that file. When all filenames have been found, the qsort()function is used to sort the array of find_t structures by filename.
The qsort() function can be found in your compiler's library. This function takes four parameters: a pointer to the array you are sorting, the number of elements to sort, the size of each element, and a pointer to a function that compares two elements of the array you are sorting. The comparison function is a user-defined function that you supply. It returns a value less than zero if the first element is less than the second element, greater than zero if the first element is greater than the second element, or zero if the two elements are equal. Consider the following example:
#include <stdio.h>
#include <direct.h>
#include <dos.h>
#include <malloc.h>
#include <memory.h>
#include <string.h>
typedef struct find_t FILE_BLOCK;
int  sort_files(FILE_BLOCK**, FILE_BLOCK**);
void main(void);
void main(void)
{
     FILE_BLOCK f_block;       /* Define the find_t structure variable */
     int ret_code;             /* Define a variable to store the return
                                  codes */
     FILE_BLOCK** file_list;   /* Used to sort the files */
     int file_count;           /* Used to count the files */
     int x;                    /* Counter variable */
     file_count = -1;
     /* Allocate room to hold up to 512 directory entries. */
     file_list = (FILE_BLOCK**) malloc(sizeof(FILE_BLOCK*) * 512);
     printf("\nDirectory listing of all files in this directory:\n\n");
     /* Use the "*.*" file mask and the 0xFF attribute mask to list
        all files in the directory, including system files, hidden
        files, and subdirectory names. */
     ret_code = _dos_findfirst("*.*", 0xFF, &f_block);
     /* The _dos_findfirst() function returns a 0 when it is successful
        and has found a valid filename in the directory. */
     while (ret_code == 0 && file_count < 512)
     {
          /* Add this filename to the file list */
          file_list[++file_count] =
              (FILE_BLOCK*) malloc(sizeof(FILE_BLOCK));
          *file_list[file_count] = f_block;
          /* Use the _dos_findnext() function to look
             for the next file in the directory. */
          ret_code = _dos_findnext(&f_block);
     }
     /* Sort the files */
     qsort(file_list, file_count, sizeof(FILE_BLOCK*), sort_files);
     /* Now, iterate through the sorted array of filenames and
        print each entry. */
     for (x=0; x<file_count; x++)
     {
          printf("%-12s\n", file_list[x]->name);
     }
     printf("\nEnd of directory listing.\n");
}
int sort_files(FILE_BLOCK** a, FILE_BLOCK** b)
{
     return (strcmp((*a)->name, (*b)->name));
}
This example uses the user-defined function named sort_files() to compare two filenames and return the appropriate value based on the return value from the standard C library function strcmp(). Using this same technique, you can easily modify the program to sort by date, time, extension, or size by changing the element on which the sort_files() function operates.
Q. How do you determine a file's attributes?
The file attributes are stored in the find_t.attrib structure member. This structure member is a single character, and each file attribute is represented by a single bit. Here is a list of the valid DOS file attributes:
Value

Description

Constant
0x00
-
Normal
-
(none)
0x01
-
Read Only
-
FA_RDONLY
0x02
-
Hidden File
-
FA_HIDDEN
0x04
-
System File
-
FA_SYSTEM
0x08
-
Volume Label
-
FA_LABEL
0x10
-
Subdirectory
-
FA_DIREC
0x20
-
Archive File
-
FA_ARCHIVE
To determine the file's attributes, you check which bits are turned on and map them corresponding to the preceding table. For example, a read-only hidden system file will have the first, second, and third bits turned on. A "normal" file will have none of the bits turned on. To determine whether a particular bit is turned on, you do a bit-wise AND with the bit's constant representation.
The following program uses this technique to print a file's attributes:
#include <stdio.h>
#include <direct.h>
#include <dos.h>
#include <malloc.h>
#include <memory.h>
#include <string.h>
typedef struct find_t FILE_BLOCK;
void main(void);
void main(void)
{
     FILE_BLOCK f_block;  /* Define the find_t structure variable */
     int ret_code;     /* Define a variable to store the return codes */
     printf("\nDirectory listing of all files in this directory:\n\n");
     /* Use the "*.*" file mask and the 0xFF attribute mask to list
        all files in the directory, including system files, hidden
        files, and subdirectory names. */
     ret_code = _dos_findfirst("*.*", 0xFF, &f_block);
     /* The _dos_findfirst() function returns a 0 when
        it is successful and has found a valid filename
        in the directory. */
     while (ret_code == 0)
     {
          /* Print the file's name */
          printf("%-12s  ", f_block.name);
          /* Print the read-only attribute */
          printf("%s ", (f_block.attrib & FA_RDONLY) ? "R" : ".");
          /* Print the hidden attribute */
          printf("%s ", (f_block.attrib & FA_HIDDEN) ? "H" : ".");
          /* Print the system attribute */
          printf("%s ", (f_block.attrib & FA_SYSTEM) ? "S" : ".");
          /* Print the directory attribute */
          printf("%s ", (f_block.attrib & FA_DIREC)  ? "D" : ".");
          /* Print the archive attribute */
          printf("%s\n", (f_block.attrib & FA_ARCH)  ? "A" : ".");
          /* Use the _dos_findnext() function to look
             for the next file in the directory. */
          ret_code = _dos_findnext(&f_block);
     }
     printf("\nEnd of directory listing.\n");
}
Q. How do you view the PATH?
Your C compiler library contains a function called getenv() that can retrieve any specified environment variable. It has one argument, which is a pointer to a string containing the environment variable you want to retrieve. It returns a pointer to the desired environment string on successful completion. If the function cannot find your environment variable, it returns NULL.
The following example program shows how to obtain the PATH environment variable and print it on-screen:
#include <stdio.h>
#include <stdlib.h>
void main(void);
void main(void)
{
     char* env_string;
     env_string = getenv("PATH");
     if (env_string == (char*) NULL)
          printf("\nYou have no PATH!\n");
     else
          printf("\nYour PATH is: %s\n", env_string);
}

No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...