473,782 Members | 2,393 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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",a rr1[i].priority);
}
/*THIS IS WHRERE THE PROBLEM OF WRITING EXISTS
*************** *********/

int filewrite(char *arr,char *arr1)
{
FILE *fp;
printf("\nopeni ng %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(f p))!=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),ic mp->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((cha r *)inet_ntoa(ip->saddr));
printf("after \n");
if(a==1)
{
b=filewrite("he lo",(char *)inet_ntoa(ip->saddr));
if(b)
printf("\n WRITten\n");
else
printf("error\n ");
}
else
{
printf("\ndoint notjjas\n");
}
display(sd, buf, bytes);
//printf("yess\n" );
}
else
perror("recvfro m");
}
else
{
// char c='1';
FILE *fp;
char c;
int oldopts;
fp=fopen("helo. txt","w");

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

fclose(fp);
printf("asdfasd fasdfasdafsdf\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_ad dr);

printf("Msg #%d\n", cnt++);
if ( recvfrom(sd, &pckt, sizeof(pckt), 0, (struct sockaddr*)&r_ad dr,
&len) > 0 )
printf("***Got message!***\n") ;
bzero(&pckt, sizeof(pckt));
pckt.hdr.type = 0;
//pckt.hdr.un.ech o.id = pid;
for ( i = 0; i < sizeof(pckt.msg )-1; i++ )
pckt.msg[i] = i+'0';
pckt.msg[i] = 0;
//pckt.hdr.un.ech o.sequence = cnt++;
pckt.hdr.checks um = checksum(&pckt, sizeof(pckt));
pckt.hdr.priori ty=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(s trings[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 5315
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
1781
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') >>> f.write('dan\n') >>> f.write('pat\n') >>> f.close()
1
4733
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 the "the batch file cannot be found" message .. how can I get rid of this .. while staying with the batch file method? here is my code: /*self deleting exe*/
2
4453
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 */ #include <time.h>
30
4588
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
2246
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 *emailmessage) { SOCKET sockfd; WSADATA wsaData; FILE *smtpfile; #define bufsize 300
7
2081
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 end of string which I do not want. Is there any library function which does not append the newline character ?
1
1952
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 clearing the buffer when I answer "yes" or anything other than "y" itself. It works perfectly when "y" is entered, now I just need to somehow accept the other yes words and clear the buffer once the "y" has been consumed. code is as follows: ...
0
1720
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 I want the latest comment to be on top, and that's where I'm running into trouble. Since I know very little about PHP, I thought I was clever in what I came up with. I think it can work if I get the coding right. Let me know if my logic is wrong. I'm...
3
4318
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
9643
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9480
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10313
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10081
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7494
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6735
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5378
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4044
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2875
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.