C File read getchar yields random EOF after 32KB
I was tasked to make a file copy over ipc shared memory. The problem is that getc randomly yeilds EOF after 32k char.
FILE* file;
int znak;
file = fopen("./source","r");
if(file != NULL)
{
while(feof(file) == 0)
{
znak = getc(file);
if(znak != EOF)
{
czekaj(0);
*adres = znak;
sygnal(1);
}
}
wait(0); //Wait for your turn
*adres = EOF;
signal(1); //Let other process go
}
Writing part as requested
int znak
FILE *plik;
plik = fopen("./plik_klient", "w");
fclose(plik);
.....
plik = fopen("./result","a");
if(plik != NULL)
{
while(znak != EOF)
{
wait(1); //Opuszczenie semafora
znak=*adres;
if(znak != EOF)
{
fputc(znak,plik);
signal(0);
}
}
}
As a result of work other process reads the info and writes it into file.
-rw-r--r--. 1 ficekba inf-17 32769 01-11 21:15 result
-rw-r--r--. 1 ficekba inf-17 1000000 01-11 21:13 source
As you can see result file has exactly 32k
1 answer
-
answered 2018-01-11 20:35
chux
Code uses
char znak
whenint znak
is best.getc()
returns anint
in the range ofunsigned char
andEOF
. This is typically 257 different values: [-1 ... 255]. When code read the filesource
and may return a 255 and assigns that to achar znak
,znak
has the value of -1 which matchesEOF
in this case. This fools code into thinking copying is done. and so may end up with a rumpresult
file.Use
int znak
.
Also open the file in binary mode is
source
may be a binary file.// file = fopen("./source","r"); file = fopen("./source","rb");
See also questions close to this topic
-
C - Singleton Pattern Implementation with double-checked locking
as you know the singleton pattern ensures a class has only one instance, and provides a global point of access to it.
We are going to implement getInstance method respect to the double checked locking using with C programming language (POSIX library) in to the given template code below. Also, we should use semaphore.
Here is my code
#include <pthread.h> #include <semaphore.h> #include <stdio.h> #include <stdlib.h> #define NO_OF_THREADS 10 struct Singleton { char *Data; }; struct Singleton *singletonObjectPointer; int addresses[NO_OF_THREADS]; sem_t sem; void *runner(void *params); /* the thread */ struct Singleton *getInstance(); int main() { int i; sem_init(&sem,0,1); pthread_t threadIds[NO_OF_THREADS]; for (i=0; i < NO_OF_THREADS; i++){ pthread_create(&threadIds[i], NULL, &runner, (void *)(i)); } /* Wait until all threads are done */ for (i=0; i < NO_OF_THREADS; i++){ pthread_join(threadIds[i], NULL); } /* Control addresses. All of them should be same */ int prevAddr=addresses[0]; for (i=1; i < NO_OF_THREADS; i++){ if(addresses[i]!=prevAddr){ printf("Object is created more than once\n"); return -1; } prevAddr=addresses[i]; } for (i=0; i < NO_OF_THREADS; i++){ printf("Singleton Addresses for each thread %x\n",addresses[i]); } printf("Successful\n"); return 1; } /** * The thread will begin control in this function */ void *runner(void *params) { int i = (int)params; printf("Thread %d\n",i); struct Singleton *s = getInstance(); addresses[i]=s; pthread_exit(0); } //Fill this method struct Singleton *getInstance(){ singletonObjectPointer = (struct Singleton *)malloc(sizeof(struct Singleton)); printf("---Address of singletonObjectPointer is %x\n",singletonObjectPointer); singletonObjectPointer->Data="This is object data"; return singletonObjectPointer; }
-
matrix multiplication error after loop in c language
I have an assignment where i have to make a matrix multiplication program more efficient so i wrote a method called multiply matrix but after i actually do the matrix multiplication in a loop the final product matrix is all zero but, if i check while in the loop its not zero
int** multiply_matrices(int** matrix1, int** matrix2, int m1, int n1, int m2, int n2) { if(n1 != m2) { printf("error\n"); return NULL; } int i = 0; int j = 0; int k = 0; int** product = (int**) malloc(m1 * sizeof(int*)); for(i = 0; i<m1; i++){ product[i] = (int*) malloc(n2 * sizeof(int)); for(j = 0; j<n1; j++){ product[i][j] = 0; } } * for(i = 0; i < m1; i ++) { product[i] = (int*) malloc(n2 * sizeof(int)); int chg = 0; while(j<n2){ if(k == n1 ){ //chg = 0; k = 0; //printf("%d\n", j); j++; } product[i][j] += matrix1[i][k] * matrix2[k][j]; printf("%d \n", product[i][j]); k++; chg = 1; } } return product;
}
-
can't get flex to recognize keyword strings
I'm trying to write a syntax highlighter for C programming language using flex. My problem is that the program stops reading input when it reaches any keyword pattern and somehow gets stuck. (the keyword definition rule is the very first rule defined in the rules section) I have no idea on why this is happening and the regex for keywords seems to like fine.
this is the code:
%{ #include <stdio.h> #include <string.h> enum token_type{ KEYWORD, ID, INTEGER, FLOAT_NUMBER, SOME_CHARACTER, SOME_STRING, SPECIAL_CHARACTER, COMMENT, MULTILINE_COMMENT, ENDING_DOUBLE_QUOTE }; int yy_left_integer; double yy_left_double; char* yy_left_string; %} %x in_multiline_comment %x in_string %option noyywrap %% "auto"|"int"|"const"|"short"|"break"|"long"|"continue"|"double"|"struct"|"float"|"unsigned"|"else"|"switch"|"for"|"signed"|"case"|"register"|"default"|"sizeof"|"char"|"return"|"do"|"static"|"void"|"enum"|"typedef"|"goto"|"volatile"|"extern"|"union"|"if"|"while" {yy_left_string = yytext; return KEYWORD;} "/*" BEGIN(in_multiline_comment); "//"[^ \n]* {yy_left_string = yytext; return COMMENT;} [a-zA-Z_][a-zA-Z0-9_]* {yy_left_string = yytext; return ID;} (("0x")[+-]?[0-9A-F]+) | ([+-]?[0-9]+) {yy_left_integer = atoi(yytext); return INTEGER;} ([+-]?[0-9]*\.[0-9]+)(E[+-]?[0-9]+)? {yy_left_double = atof(yytext); return FLOAT_NUMBER;} \" {BEGIN(in_string);} <in_string>{ [\\.?] {yy_left_string = yytext; return SPECIAL_CHARACTER;} [^\"\\]* {strncpy(yy_left_string, yytext + 1, strlen(yytext -1)); return SOME_STRING;} \" {yy_left_string = yytext; BEGIN(INITIAL); return ENDING_DOUBLE_QUOTE;} } \\(.?) {yy_left_string = yytext; return SPECIAL_CHARACTER;} \'[^ \']?\' {yy_left_string = yytext; return SOME_CHARACTER;} <in_multiline_comment>{ "*/" {yy_left_string = yytext; BEGIN(INITIAL); return MULTILINE_COMMENT;} ^[*\n]+ "*" "\n" yylineno++; } [\n] {yylineno++;} [\t\v] {} . {yy_left_string = yytext;} %% int main(int argc, char** argv) { int token; if(argc > 1){ if(!(yyin = fopen(argv[1], "r"))){ perror(argv[1]); return 1; } } FILE* highlighted_html_file = fopen("highlighted.html", "w"); if(highlighted_html_file == NULL){ printf("error opening file\n"); return 1; } while(token = yylex()){ if(token == KEYWORD){fprintf(highlighted_html_file,"<b><span style=\"color:Blue\">%s</span> </b>", yy_left_string);} else if(token == ID){fprintf(highlighted_html_file,"<span style = \"color:Orange\"> %s </span>", yy_left_string);} else if(token == INTEGER){fprintf(highlighted_html_file, "<span style = \"color:Purple\"> %d </span>", yy_left_integer);} else if(token == FLOAT_NUMBER){fprintf(highlighted_html_file, "<i><span style = \"color:Purple\">%f</span></i>", yy_left_double);} else if(token == SPECIAL_CHARACTER){fprintf(highlighted_html_file, "<span style = \"color:LightBlue\"> \"%s </span>", yy_left_string);} else if(token == SOME_STRING){fprintf(highlighted_html_file, "<span style = \"color:Red\"> \"%s", yy_left_string);} else if(token == ENDING_DOUBLE_QUOTE){fprintf(highlighted_html_file, "<span style = \"color:Red>\"</span>");} else if(token == SOME_CHARACTER){fprintf(highlighted_html_file, "<span style = \"color:LightRed\"> \"%s </span>", yy_left_string);} else if(token == COMMENT || token == MULTILINE_COMMENT){fprintf(highlighted_html_file, "<span style = \"color:Grey\"> %s</span>", yy_left_string);} else {fprintf(highlighted_html_file, "%s", yy_left_string);} } }
-
Host an electron application in a WPF based platform application
We have a plat form application developed to host all the WPF application in our organization . So basically different teams will develop there own WPF application and host there application on our Platform.Now we got a requirement where one of the team needs to host one of there electron application on our Platform.
Is there any way I can host the electron application on a .net process rather than hosting it on a node process. or Does electron has any IPC which communicate with a .net process.
-
Trying to send data from C++ to Java involving Rmq. Considering IPC Sockets
My code will be running on 2 raspberry pi's.
The Process is this:
- C++ program generates a string of data on Pi1
- Data is sent to Send Java file on Pi1
- Send Java file sends it to Rabbitmq (done and shown below)
- Recv Java file receives the message on Pi2 (done and shown below)
- Recv Java file sends it to to the C++ program on Pi2
- Process is repeated from Pi2 to Pi1
You'll see that right now I am just making the string in my Send file but that piece needs to be replaced with the data/string that is being received from the C++ file. I also need to add a part in the Recv file to send the storedMessage/message to the C++ file.
I am kind of lost on what to do from here. I looked into Sockets but didn't find anything to help me start.
I am still a novice so sorry if this seems like an easy thing. Many thanks in advance.
Recv File
import com.rabbitmq.client.*; import java.io.IOException; public class Recv { public static String recv(String ip, String Q) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(ip); factory.setUsername("test"); factory.setPassword("test"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); MyConsumer consumer=new MyConsumer(channel); channel.basicConsume(Q,true,consumer); return consumer.getStoredMessage(); } public static class MyConsumer extends DefaultConsumer { public String storedMessage; public MyConsumer(Channel channel) { super(channel); } public String getStoredMessage() { return storedMessage; } @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body, "UTF-8"); System.out.println(" [x] Received '" + message + "'"); storedMessage = message; // store message here } } }
Send file
import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; public class Send { public static void send(String ip, String Q) throws Exception { ConnectionFactory factory = new ConnectionFactory(); //set connection info factory.setHost(ip); factory.setUsername("test"); factory.setPassword("test"); //create connection Connection connection = factory.newConnection(); //create channel Channel channel = connection.createChannel(); //publish message int a = 1; while (a!=0) { channel.queueDeclare(Q, false, false, false, null); for(int i=1; i<=2; i++) { String message = "Pizza #"+i; channel.basicPublish("", Q, null, message.getBytes("UTF-8")); System.out.println(" [x] Sent '" + message + "'" + Q); } a--; } //SHUT IT ALL DOWN! channel.close(); connection.close(); } }
-
Communication between 2 process many times with message queue in C
I have some problem in IPC (Inter Process Communication). The task is making 2 program: P1 & P2. P1 create a child, P1-parent takes integer from console, send to P1-child through PIPE. P1-child receives integer and send it to P2 through Message Queue and wait for reply.Then, P1 comes back in step take integer from console, and so on. P2 receives value from P1 and reply with OK. Afterthat, P2 waits for message from P1. I did the task one time, but I can't make it done in the next time. If I add While(1) loop, P1 loop infinite in the second time. How I can make it done many times. I think the problem is the order of child and parent excute the code in P1. But I can't fix it. Here is P1 code:
if (pid > 0) { /* * 1.Accept input from console */ printf("Input a number: "); scanf("%d", &numb); sprintf(str, "%d", numb); /* * 2.Send input to child with pipe */ close(pipe_p2c[0]); write(pipe_p2c[1], str, strlen(str) + 1); close(pipe_p2c[1]); } if (pid == 0) { /* * 3.Child receive input */ close(pipe_p2c[1]); read(pipe_p2c[0], str_recv, MAXSZ); close(pipe_p2c[0]); /* * 4.Send received value to P2 by msq */ sbuf.mtype = 1; strcpy(sbuf.mtext, str_recv); printf("%s\n", sbuf.mtext); buf_length = strlen(sbuf.mtext) + 1; if((msgsnd(msqid, &sbuf, buf_length, 0)) < 0) { perror("msgsend"); exit(1); } /* * 5.Receive reply */ if((msgrcv(msqid, &rbuf, MSGSZ, 1, 0)) < 0) { perror("msgrcv"); exit(1); } printf("Received message : %s\n", rbuf.mtext); } // end if - else (pid ==0)
Here is P2 code:
if ((msgrcv(msqid, &rbuf, MSGSZ, 1, 0)) < 0) { perror("msgrcv"); exit(1); } printf("Received message = %s\n", rbuf.mtext); sscanf(rbuf.mtext, "%d", &numb); sprintf(sbuf.mtext, "%s", "OK"); sbuf.mtype = 1; buf_length = strlen(sbuf.mtext) + 1; if ((msgsnd(msqid, &sbuf, buf_length, 0)) < 0) { perror("msgsend"); exit(1); }
-
Ignoring Characters in a file read c#
I am reading a file for school and I am trying to ignore accents. I used CultureInfo but it doesn't work for me is there another way?? (example .... Clémentine = clementine)
public static void SearchName() { string lineIn = String.Empty; string[] BoatInfo = new string[5]; Console.WriteLine(); FileStream fs = new FileStream(@"FrenchMF.txt", FileMode.Open, FileAccess.Read); StreamReader inputStream = new StreamReader(fs); lineIn = inputStream.ReadLine(); string input = String.Empty; Console.WriteLine(); Console.Write("Enter Vessel Name :"); input = Console.ReadLine().ToLower().Trim(); string CheckInput = String.Empty; while(lineIn != null) { BoatInfo = lineIn.Split(','); CheckInput = BoatInfo[0].ToLower(); if (input.Equals(CheckInput)) { Console.WriteLine("its a Match" ); } else { Console.WriteLine("No Match Found!! "); return; } } }
-
Difference between f1.read() and print(f1.read()) while using escape sequences
I used the following and got different output both times but I do not know which output is coming due to which reason. The following code is:
f2=open("san.txt",'w') f2.write("sandee\np") f2=open("san.txt",'r') f2.read() Output: 'sandee\np' print(f2.read()) Output: sandee p
Also why is there a difference in quotes as in the first output there are quotes but not in the second one.
-
file handling in capl programming
please give me some hint how to perform File handling in CAPL programming. How to open and how to access the file , what and which types of functions are available for file handling.
give some suggestion regarding this topics. Thank you.