473,406 Members | 2,769 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

Problem in Writing into the file..using fputs() call

hi experts,
I need a little help in debugging this code.. would u
pleeze kindly help me?
here this program sends a datagram every 10 seconds and on reception it
cheks whether the source IP is already written in file or not.. if it
is not already entered into the file then a file is opened and that IP
is entered.
the problem is with this part..
if the filewrite() function is tested independently it is
working but in this program eventhough fputs() is returning success,
the required data is not written into the file.
how could this happen? is this related to blocking and nonblocking I/o?

i request u to kindly help me..
thanking u in advance

#include <curses.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/socket.h>
#include <resolv.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/ip_icmp.h>
#include <sys/cdefs.h>
#include <sys/types.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>

#define PACKETSIZE 64

struct hostent *hname;
struct sockaddr_in addr;
int i;
int j=0;
fd_set rset;
void ping(int);
int cont=-1,arr[20];
int cnt=1;
int flag=0;
struct icmphdr1
{
u_int8_t type; /* message type */
u_int8_t code; /* type sub-code */
u_int16_t checksum;
int priority;
};

struct icmphdr1 *icmp;

struct prio
{
int priority;
char ip1[20];
};

struct prio arr1[10];

struct packet
{
struct icmphdr1 hdr;
char msg[PACKETSIZE-sizeof(struct icmphdr1)];
};

int pid=-1;
struct protoent *proto=NULL;

/*--------------------------------------------------------------------*/
/*--- checksum - standard 1s complement checksum
---*/
/*--------------------------------------------------------------------*/
unsigned short checksum(void *b, int len)
{ unsigned short *buf = b;
unsigned int sum=0;
unsigned short result;

for ( sum = 0; len > 1; len -= 2 )
sum += *buf++;
if ( len == 1 )
sum += *(unsigned char*)buf;
sum = (sum >> 16) + (sum & 0xFFFF);
sum += (sum >> 16);
result = ~sum;
return result;
}
void sort(int js)
{
int i;
int j;

for (i = 0; i < js - 1; ++i) /* bubble sort */
for (j = js - 1; j > i; --j)
if (arr1[j-1].priority > arr1[j].priority)
{ /* check the order */
int tmp = arr1[j-1].priority;
arr1[j-1].priority = arr1[j].priority;
arr1[j].priority = tmp;
}
printf("the sorted array are...");
for (i = 0; i < js; ++i)
printf("%d\t",arr1[i].priority);
}
/*THIS IS WHRERE THE PROBLEM OF WRITING EXISTS
************************/

int filewrite(char *arr,char *arr1)
{
FILE *fp;
printf("\nopening %s\n",arr);
fp=fopen(arr,"w") ;
printf("\nthe sent string is %s\n",arr1);
if(fputs("sdf",fp)!=EOF)
return 1;
else
return 0;
}

/* the file searchin operation done here *
* */
int filesear(char a[])
{
FILE *fp;
char cs[10];
char c;
int co=0,i,n,lflag=0;
char arr[20];

strcpy(arr,a);
printf("\nthe string recieved is %s\n",arr);
fp=fopen("helo1.txt","r");

while((c=getc(fp))!=EOF && n!=0)
{
lflag=1;
if((cs[co]=c)==' '|| cs[co]=='\n')
{
cs[co]='\0';
printf("\nthe cs is %s\n",cs);
if((n=strcmp(cs,arr))==0)
printf("\nequal\n");

for(i=0;i<co;i++)
cs[i]=' ';
co=-1;
}

co++;

}
printf("\nafter while loop %s\t %d\n",cs,lflag);
printf("\nthe n=%d",n);
if(n==0)
return 0;
else
return 1;
}

/*the election algorithm must run *
* here */

//void callelec()
//{

//}
/*----------------------------------------------------------------*/
/*--- display - present echo info
---*/
/*--------------------------------------------------------------------*/
void display(int sd,void *buf, int bytes)
{ int i;
struct iphdr *ip= buf;
struct icmphdr1 *icmp = buf+ip->ihl*4;

printf("----------------\n");
fcntl(sd, F_SETFL, O_NONBLOCK);

switch(icmp->type)
{

case 0:
arr1[j].priority=icmp->priority;
strcpy(arr1[j].ip1,inet_ntoa(ip->daddr));

printf("\n\nthe prio is %d\tthe ip is
%s\n\n",arr1[j].priority,arr1[j].ip1);
j++;
if(j==5)
sort(5);
//callelec();
break;

default:
break;

}

//continue;

printf("\n");
printf("IPv%d: hdr-size=%d pkt-size=%d protocol=%d TTL=%d src=%s ",
ip->version, ip->ihl*4, ntohs(ip->tot_len), ip->protocol,
ip->ttl, inet_ntoa(ip->saddr));
printf("dst=%s\n", inet_ntoa(ip->daddr));
//if ( icmp->un.echo.id == pid )
{
printf("ICMP: type[%d/%d] checksum[%d] priority[%d] [%d]\n",
icmp->type, icmp->code, ntohs(icmp->checksum),icmp->priority,j);
}
}

/*--------------------------------------------------------------------*/
/*--- listener - separate process to listen for and collect
messages--*/
/*--------------------------------------------------------------------*/
void listener(void)
{ int sd;
struct sockaddr_in addr;
unsigned char buf[1024];
FILE *fp;
void *buf1;
buf1=buf;
struct icmphdr1 *icp;
struct iphdr *ip=buf1;
char c;
struct timeval tv;
sd = socket(PF_INET, SOCK_RAW, proto->p_proto);
//arr[j++]=icp->priority;
//printf("the prio in isteneer %d\n",arr[j]);

//callprint(arr[j]);

if ( sd < 0 )
{
perror("socket");
exit(0);
}
for (;;)
{
int bytes, len=sizeof(addr);
int m;
tv.tv_sec=10;
tv.tv_usec=0;

bzero(buf, sizeof(buf));
FD_ZERO(&rset);
FD_SET(sd,&rset);

m=select(sd+1,&rset,NULL,NULL,&tv);

printf("the size of m is %d\n",m);

if(m==1)
{
bytes = recvfrom(sd, buf, sizeof(buf), 0, (struct sockaddr*)&addr,
&len);
printf("recived\n");
if ( bytes > 0 )
{
int a,b;
printf("the before searchin\n");
a=filesear((char *)inet_ntoa(ip->saddr));
printf("after \n");
if(a==1)
{
b=filewrite("helo",(char *)inet_ntoa(ip->saddr));
if(b)
printf("\n WRITten\n");
else
printf("error\n");
}
else
{
printf("\ndointnotjjas\n");
}
display(sd, buf, bytes);
//printf("yess\n");
}
else
perror("recvfrom");
}
else
{
// char c='1';
FILE *fp;
char c;
int oldopts;
fp=fopen("helo.txt","w");

c='a';
putc(c,fp);

fclose(fp);
printf("asdfasdfasdfasdafsdf\n");
oldopts = fcntl(sd, F_GETFL, 0);
fcntl(sd, F_SETFL, oldopts | O_NONBLOCK);
}
}
exit(0);
}

/*--------------------------------------------------------------------*/
/*--- ping - Create message and send it.
---*/
/*--------------------------------------------------------------------*/
void ping(int a)
{ const int val=1;
int i, sd;
struct packet pckt;
struct sockaddr_in r_addr;

// proto = getprotobyname("OSPFIGP");
alarm(10);

bzero(&addr, sizeof(addr));
addr.sin_family = hname->h_addrtype;
addr.sin_port = 0;
addr.sin_addr.s_addr = *(long*)hname->h_addr;

sd = socket(PF_INET, SOCK_RAW, proto->p_proto);

if ( sd < 0 )
{
perror("socket");
return;
}
if ( setsockopt(sd, SOL_SOCKET, SO_BROADCAST, &val, sizeof(val)) != 0)
perror("Set TTL option");
if ( fcntl(sd, F_SETFL, O_NONBLOCK) != 0 )
perror("Request nonblocking I/O");
//for (;;)
{ int len=sizeof(r_addr);

printf("Msg #%d\n", cnt++);
if ( recvfrom(sd, &pckt, sizeof(pckt), 0, (struct sockaddr*)&r_addr,
&len) > 0 )
printf("***Got message!***\n");
bzero(&pckt, sizeof(pckt));
pckt.hdr.type = 0;
//pckt.hdr.un.echo.id = pid;
for ( i = 0; i < sizeof(pckt.msg)-1; i++ )
pckt.msg[i] = i+'0';
pckt.msg[i] = 0;
//pckt.hdr.un.echo.sequence = cnt++;
pckt.hdr.checksum = checksum(&pckt, sizeof(pckt));
pckt.hdr.priority=rand()%10;

// printf("hi helo\n");
if ( sendto(sd, &pckt, sizeof(pckt), 0, (struct sockaddr*)&addr,
sizeof(addr)) <= 0 )
perror("sendto");
cont++;
// printf("%d ji\n",cont);
//sleep(1);
}
}

/*--------------------------------------------------------------------*/
/*--- main - look up host and start ping processes.
---*/
/*--------------------------------------------------------------------*/
int main(int count, char *strings[])
{
/*struct hostent *hname;
struct sockaddr_in addr;*/

if ( count != 2 )
{
printf("usage: %s <addr>\n", strings[0]);
exit(0);
}
if ( count > 1 )
{
pid = getpid();
signal(SIGALRM,ping);
pid = getpid();
proto = getprotobyname("OSPFIGP");
hname = gethostbyname(strings[1]);
/*bzero(&addr, sizeof(addr));
addr.sin_family = hname->h_addrtype;
addr.sin_port = 0;
addr.sin_addr.s_addr = *(long*)hname->h_addr;
signal(SIGALRM,send1); */
if ( fork() == 0 )
listener();
else
ping(2);
while(1)
{
pause();
}

}
else
printf("usage: myping <hostname>\n");
return 0;
}

May 2 '06 #1
1 5279
In filewrite() you open the file but do not ever close it. The file
output is likely buffered and not written to the file until the buffer
is flushed (when the file is closed or fflush is called explicitly).

If you close the file before filewrite exits you will see the output
which is what I think you want to do.

If you really don't mean to close the file atleast call fflush.

Dave.

May 2 '06 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Kevin T. Ryan | last post by:
Hi All - I'm not sure, but I'm wondering if this is a bug, or maybe (more likely) I'm misunderstanding something...see below: >>> f = open('testfile', 'w') >>> f.write('kevin\n') >>>...
1
by: code_wrong | last post by:
Hi, I'm reading this: http://www.catch22.net/tuts/selfdel.asp (Self Deleting Executables) and playing around with the batch file method .. trouble is I always get a command box at the end with...
2
by: ajikoe | last post by:
Hi, I tried to follow the example in swig homepage. I found error which I don't understand. I use bcc32, I already include directory where my python.h exist in bcc32.cfg. /* File : example.c...
30
by: siliconwafer | last post by:
Hi All, I want to know tht how can one Stop reading a file in C (e.g a Hex file)with no 'EOF'?
11
by: zaebos | last post by:
hi, i have this code which is part of a main program, to email from within the program a log file: int MailIt (char *mailserver, char *emailto, char *emailfrom, char *emailsubject, char...
7
by: junky_fellow | last post by:
Hi guys, I want to write a null terminated string to the standard output. I don't want to use printf as it may be costly. I am using "puts" library function, but it appends the newline to the...
1
by: kelharis | last post by:
Hello, I am writing a program that will run once, and once done, ask the user if they would like to use it again. It has to work with any answer beginning with "y". I am having trouble with...
0
grassh0pp3r
by: grassh0pp3r | last post by:
Hello, I'm trying to make a very simple comments page on my site using PHP and am having problems somewhere. I am very new to PHP. I was able to create one that works with comments appended, but...
3
by: =?iso-8859-9?B?RGlu52F5IEFr5/ZyZW4=?= | last post by:
When I execute the following code #include <stdio.h> #include <stdlib.h> int main(void) { FILE *bmp; bmp = fopen("deneme.bmp","w"); fputc(10,bmp);
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.