Writing and Reading File through C Linux Code

/* Writing to a file. Reading from a file */
#include<stdio.h>
int main()
{
    //writing to file
    FILE *fpw;
    fpw=fopen("1.txt","w+");
    fputs("Hello India\n",fpw);
    fclose(fpw);

    //Reading from file
    char buff[20];
    FILE *fpr;
    fpr=fopen("1.txt","r");
    fgets(buff,20,(FILE*)fpr);
    printf("%s\n",buff);
    fclose(fpr);
    return 0;
}
/*
 Hello India
 */

---------
/*
 Writing to a file
 Reading from a file
 Writing to another file
 */
#include<stdio.h>
int main()
{
    //writing to file
    FILE *fpw;
    fpw=fopen("1.txt","w+");
    fputs("Hello India\n",fpw);
    fclose(fpw);

    //Reading from file
    char buff[20];
    FILE *fpr;
    fpr=fopen("1.txt","r");
    fgets(buff,20,(FILE*)fpr);
    printf("%s\n",buff);

        //Writing to another file
    FILE *fpo;
    fpo=fopen("22.txt","w+");
    fputs(buff,fpo);
        //fprintf(fpo,"%s",buff);
    fclose(fpr);
    fclose(fpr);
    return 0;
}
/*
 Hello India
 */

---------

/*
 Writing and reading to and from file
 */
#include <stdio.h>
int main()
{
    /*Writing to a file*/
    FILE *fp;
    fp = fopen("test.txt", "w+");
    fprintf(fp, "This is testing for fprintf...\n");
    fputs("This is testing for fputs...\n", fp);
    fclose(fp);

    /*Reading from a file*/
    FILE *fp1;
    char buff[255];
    fp1 = fopen("test.txt", "r");
    fscanf(fp1, "%s", buff);//upto space
    printf("1 : %s\n", buff );

    fgets(buff, 255, (FILE*)fp1);//upto new line
    printf("2: %s\n", buff );

    fgets(buff, 255, (FILE*)fp1);//last line
    printf("3: %s\n", buff );
    fclose(fp1);

    return 0;
    }
/*
1 : This
2:  is testing for fprintf...
3: This is testing for fputs...
 */
/*
 The functions fgets() reads up to n - 1 characters from the input stream referenced by fp. 
It copies the read string into the buffer buf, appending a null character to terminate the string.
We can also use int fscanf(FILE *fp, const char *format, ...) function to read strings froma file but it stops reading after the first space character encounters.

Sorting Numbers in File and Writing to Other File Through C Linux Code

/*Code for taking numbers from an input file sort it and write it to another output file.
  Input file contains 216543 
 Output file contains 123456 */
#include<stdio.h>
int main()
{
        FILE *f1,*f2;
        int i,j,temp,v[6],ch;
        f1=fopen("data.in","r");
        f2=fopen("data.out","w+");

        for(i=0;i<6;i++)
                fscanf(f1,"%d",&v[i]);

        for(i=0;i<6;i++)
        {
                for(j=i+1;j<6;j++)
                {
                        if(v[i]>v[j])
                        {
                                temp=v[i];
                                v[i]=v[j];
                                v[j]=temp;
                        }
                }
        }
        for(i=0;i<6;i++)
                fprintf(f2,"%d\n",v[i]);

        close(f1);
        close(f2);
        return 0;
}

------------
/*
Code for taking numbers from an input file sort it and write it to an output file.
   Input file 216543
   Output file 123456
by counting the number of lines  
*/
#include<stdio.h>
int main()
{
        FILE *f1,*f2;
        int i,j,temp,v[10],ch,n=0;
        f1=fopen("data.in","r");
        f2=fopen("data.out","w");

char line[1024];

n=0;
while(fgets(line,sizeof(line),f1)!=NULL)
n++;
/*set the file pointer to beginning*/
fseek(f1,0,SEEK_SET);


        for(i=0;i<n;i++)
                fscanf(f1,"%d",&v[i]);

        for(i=0;i<n;i++)
        {
                for(j=i+1;j<n;j++)
                {
                        if(v[i]>v[j])
                        {
                                temp=v[i];
                                v[i]=v[j];
                                v[j]=temp;
                        }
                }
        }
        for(i=0;i<n;i++)
                fprintf(f2,"%d\n",v[i]);

        close(f1);
        close(f2);
        return 0;
}

Creating Shared and Static Library in C by understanding difference between them

Difference between static(.a) and shared library(.so) ?
Archived objects(.a) i.e. static libraries are compiled into the program itself. When multiple programs/application uses the static library then multiple times same pre-compiled functions in that library gets included in to the program as well as in the main memory so size of application increases.
But shared library over comes this issue.
Shared Objects (.so) i.e. shared libraries are compiled separately and only reference/linked given such that only required functions are loaded into the memory at run time. so small size of the application as it does not contains the function code.

steps to create static library(archives) .a

step1:writing the function in library as library is nothing but set of pre compiled functions
we use funcInt(int i) and funcChar(char *charp)

/*funcInt.c:first function to be precompiled for our library*/
#include<stdio.h>

void funcInt(int i)
{
printf("\nint version library function called.\n");
}

/*funcChar:Second function to be archived in our library*/
#include<stdio.h>

void funcChar(char *charp)
{
printf("\nchar version library function called.\n");
}


step2:creating the objects files
compile the above functions with -c option which will create only object file and avoid creation of executable program.
(without -c above functions will not compile also as no main function)
gcc -c funcInt.c funcChar.c

ls *.o
it will show the created object files :
funcChar.o  and  funcInt.o

step3:creating the static library say ourlibrary by precompiling these functions and archiving it.
according to naminf=g convention it will be prefixed with lib and post fixed with .a
ar -crv libourlibrary.a funcInt.o funcChar.o
Note that lib prefixing is must.

step4: writing header file say ourheader.h having declarion of these function in ourlibrary
any application/program want to use this library must include this header file.

/*header file to be included for uing the created library*/
#include<stdio.h>
void funcInt(int i);
void funcChar(char *charp);

step5: using the created library in main funcions say funcMain.c
create the calling function in main and include the header file containing the library function declaration
#include<stdio.h>
#include "ourheader.h"/*header file to use static libraries created above*/

int main()
{
//calling the library function created
funcChar("calling the library function funcChar.");
return 0;
}

gcc -o programexecutable funcMain.c funcChar.c
OR
gcc -o programexecutable funcMain.o libourlibrary.a
OR
gcc -o programexecutable funcMain.o -lourlibrary


ms@ubuntu:~/libraryCreation$ ar -crv libourlib.a funcChar.o funcInt.o
a - funcMain.o
a - funcChar.o
a - funcInt.o
ms@ubuntu:~/libraryCreation$ gcc -o m funcMain.o libourlib.a
ms@ubuntu:~/manoj/libraryCreation$ ./m
char version library function called.

--------------
Summary:
Static Library
1. Static libraries are compiled into the program itself.
2. Program Size increases.
3.  Every  program  has  its  own  static library.

Shared Library:
1.  Shared  libraries  are  compiled separately  and  referenced  by  the program.
2.  Program  size  is  smaller  but  shared libraries are required at the run time.
3.  Shared  library  has  only  one  copy and referenced by different programs.

Process to create static library
1.  gcc -­c mylibrary.c -­o mylibrary.o
2.  ar rcs libmylibrary.a mylibrary.o

Process to create shared library
1.  gcc -­c -­fPIC mylibrary.c -­o mylibrary.o
2.  gcc ­-shared -­Wl,­soname,libmylibrary.so.1 -­o libmylibrary.so.1.0.1 mylibrary.o

Tar the source (if needed) using this command
tar-zcf libmylibrary.tar.gz libmylibrary/

How to use static library :
Compile :gcc -­static test.c -­L. ­-lmylibrary -­o statexec
Run : ./statexec

How to use dynamic/shared library :
            Compile :gcc test.c -­o dynamicexec -­L. –lmylibrary
            Run : ./dynamicexec

You May Like:

 

Threaded Concurrent echo TCP Server Code in C in Linux Platform

Concurrent Server handling Multiple Clients Code in C in Linux Platform using fork.

Iterative TCP echo Server Code in C in Linux Platform

How data packets travel source to destination over the network

C Linux Code for multi threaded socket client/Server file sharing ftp

POSIX Mutex Implementation C Program in Linux

/*POSIX MUTEX implementationstwo threads takes 2 strings and combined.Two thrads trying to read two strings from the user and combined it.If mutex not used then it may be that second string  may be read by other thread.Here, with mutex we are sharing the keyboard effectively.mutex here ensures that which ever thread gets the mutex lock will read the both strings from the user keyboard.*/#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<string.h>
pthread_mutex_t mlock;
pthread_t th1;
void *threadFunc1(void *arg);
int main()
{
        char str1[80];
        char str2[40];
        if(pthread_mutex_init(&mlock,NULL)!=0)
        {
                printf("Mutext creation failed,\n");
                exit(1);
        }
        pthread_create(&th1,NULL,threadFunc1,NULL);
        while(1)
        {
                pthread_mutex_lock(&mlock);
                printf("MAIN THREAD Enter 2 strings:\n");
                fgets(str1,40,stdin);
                fgets(str2,40,stdin);
                strcat(str1,str2);
                printf("In main Combined String is:%s\n",str1);
                        pthread_mutex_unlock(&mlock);
        }
        return 0;
}
void* threadFunc1(void *arg)
{
        char str1[80];
        char str2[80];
        while(1)
{
pthread_mutex_lock(&mlock);
        printf("thread function Enter 2 strings:\n");
        fgets(str1,40,stdin);
        fgets(str2,40,stdin);
        strcat(str1,str2);
        printf("In Thread function Combined String is:%s\n",str1);
                pthread_mutex_unlock(&mlock);
}
}
/*
MAIN THREAD Enter 2 strings:
aaaa
bbbbb
In main Combined String is:aaaa
bbbbb

MAIN THREAD Enter 2 strings:
ssss sss
dddd
In main Combined String is:ssss sss
dddd

thread function Enter 2 strings:
gggg gggg
fff fff
In Thread function Combined String is:gggg gggg
fff fff

MAIN THREAD Enter 2 strings:
sdfg
hhhhj
In main Combined String is:sdfg
hhhhj

MAIN THREAD Enter 2 strings:

*/

POSIX Semaphore Implementation Example code in C on Linux

/*POSIX semaphore Implementation for thread synchronization.
Accept string and convert its case. If semaphore is not used chances are there that input of one thread gets converted by other thread and unwanted result.
*/
#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
#include<string.h>

#define MAXMSGLEN 256

sem_t sem1;
char msg1[MAXMSGLEN];
char msg2[MAXMSGLEN];
sem_t sem2;

void* threadFunc1(void *arg);
void toggleCase(char *buf);

int main()
{
        pthread_t thread1;
        char argmsg1[]="Thread1: ";
        int res;
        int thNum;

        res=sem_init(&sem1,0,0);
        res=sem_init(&sem2,0,0);

        res=pthread_create(&thread1,NULL,threadFunc1,argmsg1);

        while(1)
        {
                printf("Print message to send:\n");
                fgets(msg1,MAXMSGLEN,stdin);
                sem_post(&sem1);
                /******wait for response****/
                sem_wait(&sem2);
                printf("Resp message: %s \n",msg2);
        }
        return 0;
}
void* threadFunc1(void *arg)
{
        printf("I am :%s \n",arg);
        while(1)
        {
                sem_wait(&sem1);
                strcpy(msg2,msg1);
                toggleCase(msg2);
                sem_post(&sem2);
        }
}
void toggleCase(char *str)
{
        while(*str)
        {
                if(isupper(*str))
                        *str=tolower(*str);
                else if(islower(*str))
                        *str=toupper(*str);
                str++;
        }
}
/*
   Print message to send:
   I am :Thread1:
   aaaaa
   Resp message: AAAAA
Print message to send:
   bbbbb
   Resp message: BBBBB

   Print message to send:
   CCCCC
   Resp message: ccccc

   Print message to send:
   asdfZXCV
   Resp message: ASDFzxcv

   Print message to send:

   WITHOUT sem OP is:
   -----------------=-
   Print message to send:
   I am :Thread1:
   qqqqqqqq
   Resp message:
   Print message to send:
   aaaa
   Resp message: QQQQQQqq

   Print message to send:
   ddd
   Resp message: AAAa

   Print message to send:
   aaaa
   Resp message: ddd

   Print message to send:
   ---------------------

*/

POSIX Mutex Implementation C Program in Linux


IPC and Sockets Programs in C in Linux Platform

IPC: Inter Process Communication means exchanging messages or data between processes.
Processes can reside on same machine or in separate machines in a network according to which IPC or Socket is used.

Traditional IPC:
1. Pipes:Only related Processes can communicate as only child can share the file descriptor of parent.
2. Fifo(named pipes): since fifo has name so it can be opened by other processes for read write.

System V IPC:
1.Message Queue
2.Semaphore
3.Shared Memory

Socket Programming/ Network programming:
Traditional and System V IPC can be used by processes whicce run on the same machine not over the Network.For the Processes that run on different machines "socket" is used. Socket can be thought of extended System V IPC. Socket Can be thought of end point of a communication channel.
Networking Programming generally follow Client Server model. Server runs forever and waits for requests from clients.Client requests for services from server. Server process the request and send to client.Browsers can be thought of http clients that requests for html pages from http/web servers.

In C programming generally Berkeleys Socket APIs are used for socket programming. Other APIS like TLI(Transport Layer Interface of system V) are also available.

Socket System Calls:

Used by Serverer           Used by client
socket()                  Socket()
bind()
listen()
accept()<----------------------connect()
read/recv/recfrom<---------write/send/sendto
write/send/sendto---------->read/recv/recfrom
close()           close()

Server Program:
First step of any network program is to create a socket using socket() system call.And, initialize the server_address with family,IP and Port.
Then created server is bind() with the server_Address and port on which then server listen() for incoming connections from client. Then server
accept() a connection from client and then read()/write() and finally close() the socket.
Client Program:
Client Program also start with creating a socket() and initialization of server socket with family,IP and port.Then connect() with the server and write()/read() and finally close() the socket.

Note:Apart from read() and write() in socket programming send()/recv() with tcp and sendto()/recvfrom() with udp can also be used.

Note :System V IPC ie message queue, semaphore and shared memory can not use read write as they are not implemented by the kernel.
Message Queue uses below API:
msgget()
msgctl()
msgsnd()
msgrcv()
Shared Memory Uses below api:
shmget()
shmctl()
shmat()
shmdt()
Semaphore uses below api:
semget()
semctl()
semop()

System V semaphore are complex so generally they are wrapped around pthread like semaphore functions.

You may like:

Threaded Concurrent echo TCP Server Code in C in Linux Platform

Concurrent Server handling Multiple Clients Code in C in Linux Platform using fork.

Iterative TCP echo Server Code in C in Linux Platform

How data packets travel source to destination over the network

C Linux Code for multi threaded socket client/Server file sharing ftp

POSIX Semaphore Implementation Example code in C on Linux

POSIX Mutex Implementation C Program in Linux


Threaded Concurrent echo TCP Server Code in C in Linux Platform

//TCP SERVER Concurrent:muliple clients can be handled by this server
//Now second client no need to wait for first client to close by finishing its task.
//This server now handles 5 clients simueltaneously. i.e. Now Upto 5 clients simueltaneously can send and receive messages from this server.
//Here concurrency is achieved  by creating a new thread which process  each new client while parent continues to accepting new connections.


#include<stdio.h>
#include<sys/types.h>//socket
#include<sys/socket.h>//socket
#include<string.h>//memset
#include<stdlib.h>//sizeof
#include<netinet/in.h>//INADDR_ANY

#define PORT 8000
#define MAXSZ 100
void* funcTask(void *arg);

int main()
{
int sockfd;//to create socket
int newsockfd;//to accept connection

struct sockaddr_in serverAddress;//server receive on this address
struct sockaddr_in clientAddress;//server sends to client on this address

int n;
char msg[MAXSZ];
int clientAddressLength;
int pid;
pthread_t serverThread;

//create socket
sockfd=socket(AF_INET,SOCK_STREAM,0);
//initialize the socket addresses
memset(&serverAddress,0,sizeof(serverAddress));
serverAddress.sin_family=AF_INET;
serverAddress.sin_addr.s_addr=htonl(INADDR_ANY);
serverAddress.sin_port=htons(PORT);

//bind the socket with the server address and port
bind(sockfd,(struct sockaddr *)&serverAddress, sizeof(serverAddress));

//listen for connection from client
listen(sockfd,5);

while(1)
{
//parent process waiting to accept a new connection
printf("\n*****server waiting for new client connection:*****\n");
clientAddressLength=sizeof(clientAddress);
newsockfd=accept(sockfd,(struct sockaddr*)&clientAddress,&clientAddressLength);
printf("connected to client: %s\n",inet_ntoa(clientAddress.sin_addr));

pthread_create(&serverThread,NULL,&funcTask,(void *)newsockfd);
}

return 0;
}
void* funcTask(void *arg)
{
int n;
int newsockfd=(int)arg;
char msg[MAXSZ];

pthread_detach(pthread_self());
while(1)
{
n=recv(newsockfd,msg,MAXSZ,0);
if(n==0)
{
close(newsockfd);
break;
}
msg[n]=0;
send(newsockfd,msg,n,0);

printf("Receive and set:%s\n",msg);
}
close(newsockfd);
}
/*
ms@ubuntu:~/ipc_socket$ gcc server.c -o s -lpthread
ms@ubuntu:~/ipc_socket$ ./s

 *****server waiting for new client connection:*****
 connected to client: 127.0.0.1

 *****server waiting for new client connection:*****
 Receive and set:India

 Receive and set:is

 Receive and set:Great

 connected to client: 127.0.0.1

 *****server waiting for new client connection:*****
 Receive and set:The

 Receive and set:USA

 */
/***************CLIENT ITERATIVE*******************/

#include<stdio.h>
#include<sys/types.h>//socket
#include<sys/socket.h>//socket
#include<string.h>//memset
#include<stdlib.h>//sizeof
#include<netinet/in.h>//INADDR_ANY

#define PORT 8000
#define SERVER_IP "127.0.0.1"
#define MAXSZ 100
int main()
{
int sockfd;//to create socket

struct sockaddr_in serverAddress;//client will connect on this

int n;
char msg1[MAXSZ];
char msg2[MAXSZ];

//create socket
sockfd=socket(AF_INET,SOCK_STREAM,0);
//initialize the socket addresses
memset(&serverAddress,0,sizeof(serverAddress));
serverAddress.sin_family=AF_INET;
serverAddress.sin_addr.s_addr=inet_addr(SERVER_IP);
serverAddress.sin_port=htons(PORT);

//client  connect to server on port
connect(sockfd,(struct sockaddr *)&serverAddress,sizeof(serverAddress));
//send to sever and receive from server
while(1)
{
printf("\nEnter message to send to server:\n");
fgets(msg1,MAXSZ,stdin);
if(msg1[0]=='#')
break;

n=strlen(msg1)+1;
send(sockfd,msg1,n,0);

n=recv(sockfd,msg2,MAXSZ,0);

printf("Receive message from  server::%s\n",msg2);
}

return 0;
}
/*
client:
ms@ubuntu:~/ipc_socket$ gcc tcpclient.c -o c
ms@ubuntu:~/ipc_socket$ ./c

Enter message to send to server:
India
Receive message from  server::India

Enter message to send to server:
IS
Receive message from  server::IS

Enter message to send to server:
Great
Receive message from  server::Great

Enter message to send to server:
*/

Threaded Concurrent echo TCP Server Code in C in Linux Platform

Concurrent Server handling Multiple Clients Code in C in Linux Platform using fork.

Iterative TCP echo Server Code in C in Linux Platform

How data packets travel source to destination over the network


C Linux Code for multi threaded socket client/Server file sharing ftp