check for zero bytes - c

I have made a piece of code that checks for zeroes in blocks of 512 bytes. A problem I have is that it doesn't seem to check all bytes if I build a check in, here is the code:
int zerocheck(FILE *fp,unsigned long long seekpoint)
{
int j;
if(fseek(fp,seekpoint,SEEK_SET)==0)
{
char buf[seekwidth],cmp[seekwidth];
if(fread(buf,sizeof buf,1,fp)==1)
{
for (j=0;j<seekwidth;j++)
{
printf("%i\n!!!\n",buf[j]);
if (buf[j]!=0)
return 1;
else
return 0;
}
}
}
return 2;
}
the print is just there for debugging. the problem is it doesn't seem to check all bytes properly if the check for a zero is there. I can see from the print that it prints out a 1 if I have a 1! but as soon as I add the if statement after it doesn't print out the 1 and doesn't return the proper value. I have no idea how to fix it...
for the record this what is happening I have a file which I KNOW the 2nd byte is a 1. if I remove:
if (buf[j]!=0)
return 1;
else
return 0;
it reads correctly and gives out this:
checking file for zeroes...
0
!!!
1
!!!
0
but if the if statement is included this is the output:
checking file for zeroes...
0
!!!
0
!!!
0
the printing is not really the issue but it is important the every byte get checked...

You only check the first byte, then return one or zero immediately! If it is zero, as expected, you need to carry on to the next byte.
Try removing the two lines that say:
else
return 0;
Then replace the final:
return 2;
with
return 0;
then your function will return zero if the entire block is zero and one if the block is non-zero.

Related

C Writing into file stop working after use it as function?

I wrote a function that sets every number of a line in a .txt file to zero and clears the other file.
I originally wrote this logic in main and it worked perfectly fine. But now I need to make a menu for my program, so I need to put this logic into a function.
That's where the things go wrong. Once I move the logic into a function, it doesn't set the numbers to zero, it just clears the file, and I didn't changed anything.
Expected result:
Workers.txt : Adam Washington Monday Friday --(use function)--> {clear}
days.txt: 1 0 0 0 1 0 0 --(use function)--> 0 0 0 0 0 0 0
Actual result:
It's clear in both files.
void ResetOwnData(){
printf("--------------------------------------------------------------------------\n");
FILE* freset = fopen ("workers.txt", "w");
close(freset);
FILE* freset2 = fopen ("days.txt", "w");
for(int i = 0; i < 7; i++){
fprintf(freset2,"%d ",i+1);
}
fprintf(freset2,"\n");
for(int i = 0; i < 7; i++){
fprintf(freset2,"%d ",0);
}
close(freset2);
printf("Everything get reset!\n");
printf("--------------------------------------------------------------------------\n");
}
There are two main things that appear to be incorrect.
You are using close rather than fclose. fclose is used with file streams (like you are using)
Your function is overwriting the one line that you want (e.g., 0 0 0 0 0 0 0) with two lines because you have two for loops
Here is a CodingGround link to the corrections that I believe you are seeking.
You should add some error checking to ensure that you truly have opened the file and that you release any allocated memory

need to provide timeout for error handling using c

I am developing a code to make communicate between two controller boards. I am passing 9 byte message from one board to another. Need to define error handling on receiver side such that it will wait for 9 byte value until timeout occurs. If timeout is reached, control should start from the 1st line of function.
currently I have defined one line like
while (/*wait_loop_cnt++<= MAX_WAIT_LOOP &&*/ counter < length);
in my code but it will remain in the same loop infinitely if doesn't receive 9 byte.
Please help thank you
Try this:
const int length = 9;
int counter = 0;
int wait_loop_cnt = 0;
while (
wait_loop_cnt++ <= MAX_WAIT_LOOP &&
counter < length) /* NO semicolon here! */
{
if (read_byte_successfully(...))
{
++counter;
}
}
if (counter < length)
{
/* Handle case of to few bytes received here. */
}

C reading file using ./a.out<filename and how to stop reading

In my class today we were assigned a project that involves reading in a file using the ./a.out"<"filename command. The contents of the file look like this
16915 46.25 32 32
10492 34.05 56 52
10027 98.53 94 44
13926 32.94 19 65
15736 87.67 5 1
16429 31.00 58 25
15123 49.93 65 38
19802 37.89 10 20
-1
but larger
My issue is that any scanf used afterwards is completely ignored and just scans in what looks like garbage when printed out, rather than taking in user input. In my actual program this is causing an issue with a menu that requires input.
How do I get the program to stop reading the file provided by the ./a.out"<"filename command?
also I stop searching at -1 rather than EOF for the sake of not having an extra set of array data starting with -1
ex
-1 0 0 0
in my real program the class size is a constant that is adjustable and is used to calculate class averages, I'd rather not have a set of 0's skewing that data.
#include <stdio.h>
int main(void)
{
int i = 0,j = 1,d,euid[200],num;
int tester = 0;
float hw[200],ex1[200],ex2[200];
while(j)
{
scanf("%d",&tester);
if( tester == -1)
{
j = 0;
}
else
{
euid[i] = tester;
}
scanf("%f",hw+i);
scanf("%f",ex1+i);
scanf("%f",ex2+i);
i++;
}
for(d = 0;d < 50;d++) /*50 because the actual file size contains much more than example*/
{
printf("euid = %d\n",euid[d]);
printf("hw = %f\n",hw[d]);
printf("ex1 = %f\n",ex1[d]);
printf("ex2 = %f\n",ex2[d]);
}
printf("input something user\n");
scanf("%d",&num);
printf("This is what is being printed out -> %d\n",num);
return 0;
}
I'm having the exact same problem. Tried every method I could find to eat the remaining input in the buffer, but it never ends.
Got it to work using fopen and fscanf, but the prof. said he prefers the code using a.out < filename
Turns out this is in fact not possible.

Use fscanf to read two lines of integers

I want to ask something that I write in C.
I use the fopen() command to open and read a text file that contains only two lines. in
first line is an integer N number, and in the second line is the N integer numbers that the first line says.
Eg.
-------------- nubmers.txt --------------
8 <-- we want 8 numbers for the 2nd line
16 8 96 46 8 213 5 16 <-- and we have 8 numbers! :)
but I want to take restrictions when the file openend.
the number N should be between 1 ≤ Ν ≤ 1.000.000. If not then show an error message. If the file is ok then the programm continue to run with another code.
Here is what I done until now:
int num;
....
fscanf(fp,"%d",&num); // here goes the fscanf() command
if(num<1 || num>1000000) // set restrictions to integer
{
printf("The number must be 1<= N <= 1.000.000",strerror(errno)); // error with the integer number
getchar(); // wait the user press a key
return 0; // returning an int of 0, exit the program
}
else // if everything works.....
{
printf("work until now"); // Everything works until now! :)
getchar(); // wait the user press a key
return 0; // returning an int of 0, exit the program
}
But the problem is that the restriction checks only for the first line number , it's correct though, but don't read the numbers in the second line.
What I mean is that :
Lets say that I have the number 10 in the first line.
The code will analyze the number, will check for restrictions and will proceed to the 'else' part
else // if everything works.....
{
printf("work until now"); // Everything works until now! :)
getchar(); // wait the user press a key
return 0; // returning an int of 0, exit the program
}
..and it will said that everything is working.
But what if I have 20 numbers in the second line? -when I need only 10
Eg.
-------------- nubmers.txt --------------
10
16 8 96 46 8 213 5 16 8 9 21 5 69 64 58 10 1 7 3 6
So I hoped be as cleared as I could. My question is that I need a code in the program, besides the 1st restriction, that have also another one restriction under the first that will read the second line of the txt file with the numbers and check if there are as many numbers as the first line says!
How do I do that?
If you guys want any other declarations feel free to ask!
Hope I was clear with my problem :)
This will check the number of integers and report too many or not enough. The integers are not saved except for each one being read into the value. Do you want to store each integer?
fscanf(fp,"%d",&num); // here goes the fscanf() command
if(num<1 || num>1000000) // set restrictions to integer
{
printf("The number must be 1<= N <= 1.000.000",strerror(errno)); // error with the integer number
getchar(); // wait the user press a key
return 0; // returning an int of 0, exit the program
}
else // if everything works.....
{
int i = 0;
int value = 0;
while ( fscanf ( fp, "%d", &value) == 1) { // read one integer
i++; // this loop will continue until EOF or non-integer input
}
if ( i > num) {
printf ( "too many integers\n");
}
if ( i < num) {
printf ( "not enough integers\n");
}
getchar(); // wait the user press a key
return 0; // returning an int of 0, exit the program
}
use a loop that takes the first num and checks is is the number of integers in next line:
int z = num;
while(z--){
if (getchar() == EOF)
printf("err")
}
Do it like this:
fscanf(fp,"%d",&num);
// next lines of code (restrictions). Then place the below code before getchar in the else
int temp[num+1];// space to store num integers to temp and 1 space to check for extra number
for(i=0;i<num;i++)
{
if(fscanf(fp,"%d",&temp[i]) != 1)// fscanf will automatically read 2nd line and store them in temp array
//error ! Less numbers in file !
}
if(fscanf(fp,"%d",&temp[num]==1) //if still numbers can be scanned
//Extra numbers found in line 2

Finding lengths between the elements of an event

I have a matrix which has 1's,-1's and zeros.. say
state=[1; 1; -1; 1; -1; 0; 0; 0; 0; 0; 0; 0; 0; 1; 0; -1; 1; 0; -1.........];
Say -1 is the start of an event and 0 contributes to the length of it when its between (-1 and 1) as -1 remains the start and 1 is the end of event. But when 0 comes after a 1 that means it doesn't have any value to it as the event ended recently; can't take that into consideration.
So I need to get the number of such events that happened and also lengths of those events in the entire matrix for such events so my output would be
result=[2 10 2........]
and need the no of such events.
And in the above case I would exclude my first two indices which are 1's that doesn't contribute to anything.
It sounds simple but its been a while I got back to matlab. This is what I tried but it fails as it takes the zeros in between 1 and -1 as it should be excluded:
result=[find(state==-1)-find(state==1)];
which is wrong.
Your help is appreciated.
Follow these steps:
Find all starts and all ends.
For each start, find the end immediately after it.
Subtract each end found in step 2 minus each corresponding start, and don't forget to add 1.
The number of events is immediate from that.
The interesting part is step 2. bsxfun tests, for each combination of start and end, if the start is less than the end. Then the second output of max gives the index of the first true value for each start, if any; and its first output tells you if there really was some true value, (that is, if the found index is valid).
starts = find(state(:)==-1); % // step 1
ends = find(state(:)==1); % // step 1
[valid, next_end] = max(bsxfun(#lt, starts.', ends)); %'// step 2
result = ends(next_end(valid)) - starts(valid) + 1; % // step 3
number = numel(result); % // step 4

Resources