C

22K

Solutions

13K

Contributors

C is a general-purpose, imperative computer programming language, supporting structured programming, lexical variable scope and recursion, while a static type system prevents many unintended operations. By design, C provides constructs that map efficiently to typical machine instructions, so it has found lasting use in applications that had formerly been coded in assembly language, including operating systems as well as various application software for computers ranging from supercomputers to embedded systems. It is distinct from C++ (which has its roots in C) and C#, and many later languages have borrowed directly or indirectly from C.

Share tech news, updates, or what's on your mind.

Sign up to Post

I want to read a file, and look for line A, and then look for line B, and then look for line C. Currently I have something like:

with open(infile, 'r') as inf:
    for line in inf:
        #do something with each line until we come to line A
        if line == A:
            #we found line A. Keep reading lines until we come to line B
            #do something with each line until we come to line B
            if line == B:
                #we found line B. Keep reading lines until we come to line C
                #do something with each line until we come to line C
                if line == C:
                    #Hooray!

Open in new window

Now I want to convert this to something nicer, like a state machine:
def initial_state()
    read lines from inf
        do something with each line until we come to line A
        if line == A:
            found_line_A()
            
def found_line_A()
    read lines from inf
        do something with each line until we come to line B
        if line == B:
            found_line_B()
            
def found_line_B()
    read lines from inf
        do something with each line until we come to line C
        if line == C:
            #Hooray!

with open(infile, 'r') as inf:
    initial_state()            

Open in new window

How can I read lines from the same input file inf in each of the three functions above?
0
Webinar: Miercom Evaluates Wi-Fi Security
Webinar: Miercom Evaluates Wi-Fi Security

It's not just about Wi-Fi connectivity anymore. A wireless security breach can cost your business large amounts of time, trouble, and expense. Plus, hear first-hand from Miercom how WatchGuard's Wi-Fi security stacks up against the competition in our upcoming webinar!

Hi Experts,

I need your help as I'm new to programming.  Could you please help me out with a solution for the below program?

The program simulates different errors that the protocol checks for.

           Modify the program so that it implements "time out".

          Theory:

          Sender: sends a frame and calls a SIGALRM function and sets the timer

           for say 2 seconds. If the sender gets a response within two seconds

           from the receiver (either "ACK" or "NAK"), turn off the alarm and

           transmit the next frame. If no response is received, time out function

           kicks in and retransmits the frame.

           Receiver: When it sees an error in transmission, do not send back

           anything to the sender and this causes the time out and retransmit.


sender_c.txtreceiver_c.txt
0
Link to the problem:

The code works fine on my own system, but while submitting shows wrong answer?

 
   #include <stdio.h>
    void main()
    {
    	int t, n, count;
    	scanf("%d", &t);
    	while(t--)
    	{
    		count=0;
    		scanf("\n%d",&n);
    		while(n>0){
    		if(n%10==4)
    		{
    			count++;
    		}
    		n=n/10;
    	}
    	printf("\n%d", count);
    	}
    }

Open in new window

0
Hi I am trying make a deep copy of the structure below which will contain the decoded video frames and copy to a new element in a vector without each previous element being overwritten.
The structure below is being populated as the memory in debug mode is increasing as expected with each pass of the while loop.
struct YUV_Buffer
 {
mfxFrameSurface1  *mSurface;
YUV_Buffer(mfxFrameSurface1 *pBuf = { 0 })
    : mSurface(new mfxFrameSurface1[sizeof(mfxFrameSurface1)])
{
    memcpy(mSurface, pBuf, sizeof(mfxFrameSurface1));
}

YUV_Buffer(const YUV_Buffer& YuvBuf) 
 : YUV_Buffer(YuvBuf.mSurface)  
{}

YUV_Buffer& operator = (YUV_Buffer YuvBuf) {

    std::swap(mSurface, YuvBuf.mSurface);
    return *this;
}

~YUV_Buffer() {
        MSDK_SAFE_DELETE_ARRAY(mSurface);
}
  };

Open in new window

I am calling the structure and copying the elements into the vector with each iteration of the while loop "mfxFrameSurface1 pVPPSurfacesOut[nSurfIdxOut]" contains all the information regarding the decoded video frame I need to copy pVPPSurfacesOut[nSurfIdxOut] to the vector mBuffer.push_back(root) using a deep copy so the data that the pointers in the structure are pointing to are also copied but what is actually happening is the last frame processed is overwriting all previous elements in the vector. Each time the loop passes like this: I have removed the code that is decoding each frame as its no relevant I just need to work out why the elements are getting overwritten in the vector
while(1){
std::vector<YUV_Buffer> mBuffer;
YUV_Buffer root(pVPPSurfacesOut[nSurfIdxOut]);
mBuffer.push_back(root);
}

Open in new window

each iteration of the while loop populates pVPPSurfacesOut[nSurfIdxOut] structures which contain pointers with video information like height width buffersize … and the video data its self in a NV12, YUV420 colour space, I need to access each frame from the vector mBuffer but when I try to access the vector mBuffer[0]… Im getting the last frame copyed to the vector.

Regards Nigel
0
I had this question after viewing Using AT commands with C.

I'm doing a project and want to connect my gsm "click" to my phone USING C PROGRAMMING, have it wired up ok just the program is letting me down..... [ I want the gsm to send a message to my phone ]
The GSM is connected to the UART serial port of my 8051f020 microcontroller, any help much appreciated my program is as follows:


      
 void send_it (void) interrupt 4 using 1   // This is the ISR 
	
	{  
		
		TI0 = 1; // TI must be cleared by software when writing directly  
	                       // to SBuf  as shown in the previous program – However,   
                   // the  Printf function requires TI to equal “1” on entering
		          // the function.
		printf ("Hello \n\n");  
   		printf ("This text was sent to the Uart using Printf \n\n"); 
		
    printf("AT+CMGF=1<CR>%c\n\n"); // configured the GSM module to SMS mode                                     
    printf("AT+CMGR=3<CR>\n\n");       

    ("AT+CMGS=\"08******\"HELLO"); // send mobile number to the GSM           
       
   
	}

Open in new window

0
I am in need of an Excel macro that will perform the following:

Compare two columns of stock symbols that are numerically listed and the results of the comparison displayed in a third column.  I’m looking for stocks in column B that have improved in their numerical order (one being the best) from their listing in column A.  The results would be displayed in new column C, and the entries would be listed in order of those making the best improvement at the top.

Considerations:
•      Columns A and B contain 200 entries (rows) each.  No blank cells in either column A or B.
•      Column B may have symbols that are not contained in column A.  
•      Symbols in column B not listed in column A would receive the highest ratings in column C.
•      If there are two or more symbols in column B that are not in column A, the symbols in column B would be ranked accordingly in column C.

Example of conditions for column C listing using attached example file: Two columns of Symbols.xlsx.
•      Symbol ARDM is listed in column B but not column A, so it goes to the top of the list in column C and is listed alphabetically (preferred, but not necessary).
•      Symbol FCRE also listed in column B but not column A, so it goes to the top of the list in column C and is listed alphabetically (preferred, but not necessary).
•      ATNM was 151 in column A, and is 8 in column B, a gain of 143, so it would go above CADC, which was 91 in column A and is 10 in column B for a gain of 81.
•      CADC would go above NEPT …
0
Hello sir,
I am creating windows application using C# 2010 - Here i am using 3 forms
in my first form place a one data grid view and enter 6 rows but i am enter below format (it's stored at 2 empty rows)
EX :
Sl.No      Name       Age
1      A      10
2      B      11
3            
4            
5      C      12
6      D      13

Like this format - it's successfully stored at sql db.
--------------------------------------------------------------------------------------------------------------
IN my second form i am using approximately 10text boxes and enter 10 text boxes vales stored at sql db.
-------------------------------------------------------------------------------------------------------------
IN MY 3rd FORM
placed 2 drop down list and below one data grid view, here i am select  1st drop down(it's binding a first form db) records are display my 3rd form data grid view same as to form1 like below example,
but here i want
I am select a 2nd drop down binding a records 2nd form db. in my empty space cells how to display seconds form text box values as an row 3rd,& 4th rows.
Sl.No      Name       Age
1      A      10
2      B      11
3            
4            
5      C      12
6      D      13

any one give me suggestions.
0
Actually I have given a task to create an ini prase and Reding writing updating all these thing in c can you please help me something I have already attach an attachment  pls reply fast
0
The code snippet below is part of the restaurant menu program you previously used in the lab. Add a choice for a drink. Add the necessary code to allow the program to calculate the total price of order for the user. Assume the following price list:

Hamburger $5
Hotdog $4
Fries $3
Drink $2

The program should allow the user to keep entering order until choosing to exit. At the end the program prints an order summary similar to this:

You ordered 2 hamburger(s), 1 hotdog(s), 3 fries, 0 drink(s).

Price: $23
HST:  $2.99
Total: $25.99

=================================
Code snippet
===============================
do {

printf("What do you want to eat today?\n");
printf("1. Hamburger\n");
printf("2. Hotdog\n");
printf("3. Fries\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch(choice) {
case 1:
printf("You ordered a hamburger\n");
break;
case 2:
printf("You ordered a hotdog\n");
break;
case 3:
printf("You ordered fries\n");
break;
case 4:
printf("Order finished, thank you!\n");
break;
default:
printf("Wrong choice! try again: ");
}

} while (choice != 4)

Open in new window


needhelp in these ASAP
0
Hi
I am stucked in a project, where I have to convert some audio:
The Audio is PCM 16bit big endian 16Khz stereo & Ulaw 8bit 8000hz. Have to be able to go both ways.
Do you have any recommended Libs or even better software examples that will help me doing it :)

I get the audio in the PCM format as Callback data.
static int stream_GSMdata_2_ulaw(int16 id, char* data, uint32 size)
...
And after the conversion to Ulaw I need to send the RTP packets in 60 ms chunks (480bytes) via UDP:
 SendRTPData(myData);

Any help is appreciated :)
0
Learn SQL Server Core 2016
LVL 12
Learn SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

Need several WIX form drop-down boxes to have the data filtered on the previous drop-down results.  I found an example of utilizing a states.jw (??) import tool for states of the United States that is evidently 'built in' to WIX, however, my data is in another WIX database / dataset collection.    So, to be clear, the available drop down choices for drop box B is dependent (filtered) based on the results of drop-down A; the available drop down choices for drop box C is dependent (filtered) based on the results of drop-down B.  there are only these three dependent drop-downs at the moment.

Any step-by-step instructions would be absolutely fantastic!!  <<thanks in advance>>
0
I am working on creating an android app that scans the deleted data which is not overwritten by android device and recovers it, just like data recovery tool. How to create a recovery tool inside an android app is there a tutorial or any thing?
0
First of all I am doing a program kinda simple long program, here is the full details:

The P-v-T relation for real gases can take many forms. The simplest relations are the ideal gas equation and the Van der Waals equation. These relations are to be applied to superheated steam. The file “pvt.txt” contains the P-v-T data of superheated steam (10 – 800 kPa) for the temperature range of 200 oC through 1200 oC, obtained from the steam tables.

Write a C program to read the steam table data “pvt.txt”. In the C program, estimate the density of steam for the pressure range 10 through 800 kPa, and temperature range 200 oC through 1200 oC,

(1) Using the ideal-gas relation: m3/kg where R = 0.4615 kJ/kgK, T is temperature [K] and P is pressure [kPa].

(2) Using the Van der Waals equation:

where R = 0.4615 kJ/kgK, T is temperature [K] and P is pressure [kPa]. The constants are obtained from and where Pcr = 22060 kPa and Tcr = 647.1 K.

In each case, calculate the resulting percentage error of the estimated density as follows: Error = x 100% Submit a report which must include: 1. Introduction, algorithm or flowchart, the C program, and the density from steam table. 2. The estimated density table when using the ideal gas equation. 3. The percentage error table when using the ideal gas equation. 4. The estimated density table when using the Van der Waals equation. 5. The percentage error table when using the Van der Waals equation. 6. Discussion and conclusion. Note: Density…
0
void mainImage( out vec4 fragColor, in vec2 fragCoord ) 
{
    vec2 px = vec2(1.0) / iResolution.xy;
    vec2 pos = fragCoord.xy / iResolution.xy;
   
    vec4 color =  texture(iChannel0, pos);
    vec4 origColor = color;
    float numSamples = 1.0;

    {
    	for (float x = -8.0; x <= 8.0; x += 1.0)
    	{
        	for (float y = -8.0; y <= 8.0; y += 1.0)
    		{
	        	vec4 addColor = texture(iChannel0, pos + (vec2(x, y) * px));
                if (max(addColor.r, max(addColor.g, addColor.b)) > 0.3)
                {
                    float dist = length(vec2(x,y))+1.0;
                   // if (dist <= 5.0)
                    {
                        vec4 glowColor = max((addColor * 128.0) / pow(dist, 2.0), vec4(0.0));
                        if (max(glowColor.r, max(glowColor.g, glowColor.b)) > 0.0)
                        {
                			color += glowColor;
            				numSamples += 1.0;
                        }
                    }
                }
        	}
    	}
    }
    
    fragColor = mix(origColor, color / numSamples, 0.05);
    fragColor.a = 1.0;
}

Open in new window


Could you help me in converting this shader to #version 120 pleasee?
0
Dual pipe producer/consumer blocked by read.

The issue is in the producer:
        read(consumer_to_producer[0], &cnt, sizeof(cnt));
        read(consumer_to_producer[0], shared_arr, sizeof(shared_arr));

Open in new window

prevents the producer from working because the consumer has yet to write anything, how can I avoid this?


#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10

int shared_arr[SIZE];
int cnt = 0, in = 0, out = 0;
int consumer_to_producer[2], producer_to_consumer[2];

void consumer();
void producer();

int main() {
    pipe(consumer_to_producer); // consumer to producer
    pipe(producer_to_consumer); // producer to consumer

    if (fork() == 0) {
        /* child process */
        consumer();
    } else {
        /* parent process */
        producer();
        sleep(3);
    }

    exit(0);
}

void consumer() {
    /* consumer process */
    close(producer_to_consumer[1]); // Close write end, we don't need it
    close(consumer_to_producer[0]); // This fcn doesn't need read end
    while (1) { 
        /* if buffer is full, consume it */
        // read in cnt from producer so we can check if it's full
        read(producer_to_consumer[0], &cnt, sizeof(cnt));

        if (cnt == SIZE) { /* If full, consume */
            read(producer_to_consumer[0], shared_arr, sizeof(shared_arr));
            printf("I am consuming\t%d\t%d\n", shared_arr[in], out);
            out = (out + 1) % SIZE;
            cnt--;
        } 

        

Open in new window

0
I've got a style/control template for a ListView which is a variant on the default (attached).

However, I can't for the life of me figure out how to change the colours of the selected row in the ListView and the MouseOver item. At the moment the selected item and the hovered item's background is too bright.

Bright!
I've tried adding a Style for a GridView but I get a message saying this isn't supported.

Am I missing something in the ListView control template? Where are these "default" colours coming from?
listview.xaml
0
Write a C program to calculate the total size of the files in a directory and the sub-directories of the directory. 
0
Can someone please help to create regular pattern in c using regex.h to match sub string without matching terminating . character.

For example, from below string pattern should match “hello world.” and “hello world” (there is no . char at the end of second match)

|hello world.|hello world.

Thanks for your input!
0
I need help to build regular expression pattern in c using regex.h. I have a string having pipe separated fields.

foo|this is first field.|this is second field.|this is third filed.

I have to create pattern at run time to  match complete field by sub string of it.  for example "second" will match  "this is second field." and "first" will match "this is first field." but "third" should match "this is third filed"  without including terminating . character.

If there are more then one . at the end then it should match them except last . character for example if third filed is "|this is third field..." then it should match "this is third field.."

can some one please help to create this pattern.
0
Challenges in Government Cyber Security
Challenges in Government Cyber Security

Has cyber security been a challenge in your government organization? Are you looking to improve your government's network security? Learn more about how to improve your government organization's security by viewing our on-demand webinar!

hi
i need to call dll file wrote by c programming in oracle 6i  form

here the code


const hasp_feature_t feature = 8;
hasp_handle_t handle = HASP_INVALID_HANDLE_VALUE;
hasp_status_t status;
unsigned char vendor_code[] =
"P+bvguFqumejqvwOmvNDruTN3d0v";
status = hasp_login(feature, vendor_code, &handle);
/* check if operation was successful */
if (status != HASP_STATUS_OK)
{
    switch (status)
    {
        case HASP_FEATURE_NOT_FOUND:
            break;
        case HASP_HASP_NOT_FOUND:
            break;
        case HASP_OLD_DRIVER:
            break;
        case HASP_NO_DRIVER:
            break;
        case HASP_INV_VCODE:
            break;
        case HASP_FEATURE_TYPE_NOT_IMPL:
            break;
        case HASP_TMOF:
            break;
        case HASP_TS_DETECTED:
            break;
        default:
            break;
    }
}
0
I have a kernel module, in which :

It changes the saddr field of outgoing packets and fixes it back(daddr) in incomming packets ...
I'm calculating new checksum for ip and tcp headers ...
So in client side I change ip - server side receives it(SYN packet) and sends (SYN-ACK) packet - but client side - sends (Reset) packets and trying again to process tcp handshake ...

I've seen to another kernel-module examples - dnat/snat - my code is analogical ? My be ebtables make my hooks to work incorrect ?

Interfaces: eth0 - XXX.XXX.XXX.1 eth0:0(alias) - XXX.XXX.XXX.2
Client (original ip XX.XX.XX.1(eth0) and XX.XX.XX.2(eth0:0))
                                                               SERVER (ip YY.YY.YY.YY)

     USER-SPACE app creates tcp-socket and connects to (YY.YY.YY.YY)

     1) 
     TCP (SYN) -----------(packet ip XX.XX.XX.1-YY.YY.YY.YY[ip.sum1, tcp.sum1] )----->
     NF_INET_POST_ROUTING ( ip XX.XX.XX.2-YY.YY.YY.YY[ip.sum2, tcp.sum2] )
     ================================================================================>


     2)
     <-------TCP (SYN ACK) ------(packet ip YY.YY.YY.YY-XX.XX.XX.2[ip.sum1, tcp.sum1])
     NF_INET_PRE_ROUTING ( ip YY.YY.YY.YY-XX.XX.XX.1[ip.sum2, tcp.sum2] )
     <================================================================================


     3)

     TCP (RST) - against TCP (ACK) - that is the question ....
     ================================================================================>

Open in new window

/* 

Open in new window

0
If i want to create a database of students Information using structure and store in FILE,how to count how many student's information are there in that FILE using C language?
0
My Code:

#include <stdio.h>

int main(int argc, char *argv[]){
  char line1[128];
  char line2[128];
  char line3[128];
  char rem_text[128];
  FILE *f;

  f = fopen((argv[1]), "r");
  if (!f) {
     printf("error");
  } else {
      fscanf(f, "%127[^\n]\n%127[^\n]\n%127[^\n]\n%127[^\n] ", line1, line2,line3, rem_text);
      printf("1:%s\n", line1);
      printf("2:%s\n", line2);
      printf("3:%s\n", line3);
      printf("4:%s\n", rem_text);
      fclose(f);
  }

  return 0;
}

Open in new window

The Program works almost as expected, except for one detail. What it is supposed to do is, take the first three lines of a file and store them in individual variables. (which works) but then I would like to store the entire remaining bit of the file into its own variable. How do I do that? Thanks in advance

If for example my test.txt file contains:
`Kapitel 1`
`chapter_21.txt`
`chapter_42.txt`
`'Would you tell me, please, which way I ought to go from here?'
'That depends a good deal on where you want to get to,' said the Cat.
'I don't much care where -' said Alice.
'Then it doesn't matter which way you go,' said the Cat.
'- so long as I get SOMEWHERE,' Alice added as an explanation.
'Oh, you're sure to do that,' said the Cat, 'if you only walk long enough.'`

I would like to store` Kapitel 1` as `Title`

`chapter_21.txt` as `chapter_a`

`chapter_42.txt` as `chapter_b`

and

`'Would you tell me, please, which way I ought to go from here?'
'That depends a good deal on where you want to get to,' said the Cat.
'I don't much care where -' said Alice.
'Then it doesn't matter which way you go,' said the Cat.
'- so long as I get SOMEWHERE,' Alice added as an explanation.
'Oh, you're sure to do that,' said the Cat, 'if you only walk long enough.'` as `rem_text`
0
Hi,

I am developing an application for "Bus Driver" where one of important feature is to calculate Odometer inside Android app itself.

Problem Statement : My odometer calculation is working on Google Nexus 10" Tablet and but it is not working on Acer Iconia 10" Tablet.

I have used different method to calculate distance between two different (Latitude, Longitude)

Method 1 : Haveshine Formula
double dlon = Math.toRadians((vCurrent_lon - vLast_lon));
                        double dlat = Math.toRadians(vCurrent_lat - vLast_lat);

                        Log.i("CalcDistance ", " 2 ");

                        double a = Math.pow(Math.sin(dlat / 2), 2) + Math.cos(Math.toRadians(vCurrent_lat)) * Math.cos(Math.toRadians(vLast_lat)) * Math.pow((Math.sin(dlon / 2)), 2);
                        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

                        double vRADIUS_OF_EARTH = 3961;

                        //vDistanceBetweenTwoLocation = 3961 * c;
                        vDistanceBetweenTwoLocation = vRADIUS_OF_EARTH * c;

                        //================= Rounding Odometer upto 02 digits ==================================
                        Lib_Yukti_Common_Util vLib_Common = new Lib_Yukti_Common_Util();
                        vDistanceBetweenTwoLocation = vLib_Common.Round(vDistanceBetweenTwoLocation);
                        //====================================================================================
Method 2  : distanceTo

public static final float calculateDistanceTo(Location fromLocation, Location toLocation) {
    return fromLocation.distanceTo(toLocation);
}



Thanks in Advance
0
HI!
I was going to work with sounds in C. I just wanted to know if this is possible to write my own "library" with the standart libraries of C
as i don`t want to obey any rules of sound libraries out there like OpenAl, PortAudio, BASS etc. I really want to do some work by myself which handles just microphone of my laptop, record  voice, keep it in a "buffer" and play it, that`s all. Nothing else.
Can you guys PLEASE help, where and how to start sharing your experience with me?
Any suggestions are very much apprecieted!!!
0

C

22K

Solutions

13K

Contributors

C is a general-purpose, imperative computer programming language, supporting structured programming, lexical variable scope and recursion, while a static type system prevents many unintended operations. By design, C provides constructs that map efficiently to typical machine instructions, so it has found lasting use in applications that had formerly been coded in assembly language, including operating systems as well as various application software for computers ranging from supercomputers to embedded systems. It is distinct from C++ (which has its roots in C) and C#, and many later languages have borrowed directly or indirectly from C.

Top Experts In
C
<
Monthly
>