Search the Community
Showing results for tags 'programming languages'.
-
One of the useful statements that we can use in the C programs is the goto statement. Even though its sometimes discouraged for making code unreadable, it’s a fundamental feature of the C Language that is sometimes needed. This statement allows us to control the flow of a program by jumping to and from various parts of the program. In this tutorial, we will learn what this statement does, how it works, and the various instances it can come in handy. NOTE: It is good to keep in mind that the goto statement is not widely used. It tends to create some unnecessarily complex code but it can be effective, and learning about it can help you avoid its pitfalls. goto Statements Goto, as the name suggests, allows us to transfer the control of a program from one part to another without using any conditional statement evaluation. It provides a form of low-level and manual control flow. Unlike the conditional statements that evaluate a condition and then perform an action, the goto statement just switches to another part of the code without any context. As a result, it often leads to spaghetti code which is basically a code that is hard to understand due to lack of defined structure or foundation on the resulting actions. Think of a bowl and twisted spaghetti, using the goto statements incorrectly can lead to such a code that makes you want to off yourself due to lack of coherent structure in the execution. What does goto do? In simple terms, when the program encounters a goto statement, the program jumps to the specified label which automatically bypasses any code that is defined between the goto statement and the target label. You can use it to, for example, break out of a loop, handle the errors, or simply with complex cases of nested statements. goto syntax The following shows the basic syntax of the goto statement in C: goto label; //... label: // logic at the label We start with the “goto” keyword followed by the name of the label that we wish. We then call the actual label and specify the code that we wish to run. Example: Break Out of a Loop with goto Let us look at a basic example that demonstrates the use of the goto statement to break out of a loop: #include <stdio.h> int main() { int i = 0; start: printf("Value of i: %d\n", i); i++; if (i < 5) goto start; return 0; } In this example, we start by declaring a positive integer variable and initialize its value to 0. We then create a label called “start”. In C, the labels are followed by a colon to denote that they are targets for the goto statement. In the label, we print the value of “i” to the console and increment the value of “i” by 1 on each iteration. Next, we setup a goto statement that unconditionally jumps to the “start” label. This creates a loop that jumps back to the start label as long as the value of “i” is less than 5. Run the previous code as follows: Value of i: 0 Value of i: 1 Value of i: 2 Value of i: 3 Value of i: 4 It is good to keep in mind that if you want to deal with loops in a more effective and efficient manner, use other constructs such as the “for” and “while” loops. Unless you closely examine the given code, you can hardly tell that there is a loop in the code. Conclusion In this tutorial, we explored the fundamentals and workings of the goto statements in C/C++, how it works, and how to use it. We strongly recommend to avoid using the goto statements unless you explicitly need to. View the full article
-
- programming
- programming languages
-
(and 1 more)
Tagged with:
-
The C language has several functions that allow to read the files, the most commonly used are the read() and fread() functions. This language also provides methods to read the character by character with functions such as getchar(). It is important to know the file processing functions, their call methods, input and output arguments, etc. in order to use them fluently because they are the available resource to the programmer to store and dispose off the information that is stored in the system. In this Linuxhint article, you will learn how to use the read() function to read the files. We’ll explain everything about this ella, its syntax, the method call, the input and output arguments, the type of data they each accept, and how to declare them properly. We then apply what we learned by putting the use of this feature into practical examples. In order for you to be fully aware on how to use the read() function, we added a special section that describes all the errors that can occur when using this function, as well as their detection and identification, so that you will have the necessary techniques for a quick solution in case of an error. Syntax of the Read() Function in C Language size_t read(int fd, void *buf, size_t count); Description of the Read() Function The read() function reads the contents of the open file that is specified by its descriptor in the “fd” input argument. This function reads and copies the contents of the file into the buffer that is pointed to by “buf” with the count number of bytes. The “fd” identifier is an integer that is returned as the result of the open() function when the file is opened. If the read() function returns successfully, it returns the number of bytes read. A result equal to 0 means that the file was read to the end, and -1 means that an error occurred. The specific error can be identified by retrieving its code from the global “errno” variable. Later, you will find a section that describes the errors that can occur when using the read() function and the techniques to detect and identify them. The read() function is declared in the “unistd.h” header. To use it, you must include this file in your code as follows: #include <unistd.h> How to Read a File with the Read() Function In this example, we will explain how to open and read a file using the open() and read() functions. For this purpose, we previously created a text file with the “example.txt” name via the Linux Manager and saved it in the “Documents” directory. Then, we wrote the first paragraph of this article in it. The first step in developing the code to read the file is to include the necessary headers and create a main() function that returns an empty value. We define the “fd” integer in it which serves as the file descriptor, a 1024 character buffer called “buff” where the information that is read by read() is stored. The array path stores the path and the name of the file that we want to read. After defining the necessary variables, we call the open() function to open the file. We call this function by passing the path array with the path and name of the file as the first input argument and specifying the O_RDONLY flag as the second argument. As the output argument, we pass the “fd” integer where open() returns the descriptor that we then use to read to the file. Once we have the file open, we read its contents by calling the read() function and passing the “fd” descriptor as the first argument that is returned by the open() function. As the second argument, we pass the pointer to the “buff” buffer where we store the contents to be read and finally the size of the buffer which, in this case, is 1024 bytes. We then use the printf() function to display the contents that are stored in buff in the command console. Here is the complete code for this example: #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> int main() { int fd; char buff[1024]; char path[] = "Documents/example.txt"; fd = open(path, O_RDONLY); read(fd, buff, 1024); printf("\n\n%s\n\n",buff); } In the following figure, we see the compilation and execution of this code. As we can see, read() puts the entire contents of the “example.txt” file into “buff” and the printf() function prints it to the command console: How to Detect and Identify the Errors that Can Occur When Using the Read() Function Using read() can generate various errors. When this happens, this function returns a result that is equal to -1. The easiest way to determine if an error has occurred is to use an “if” condition where the condition is the return value of -1. Now, let us see how you can use this method to determine if an error has occurred: int n; n = read(fd, buff , 1024); if ( n == -1){ printf ("An error occurred while trying to read the file."); } If the read() function returns with an error, it transitions to the “if” statement and prints the “An error occurred while trying to read the file” message. When an error occurs, a numeric code is automatically stored in the global “errno” variable which is defined in the “errno.h” header. This code can be used to identify the error that occurred. The following is an excerpt with the errors that the read() function can generate and that are defined in the “errno.h” header, along with a brief description of each error and the associated integer value: Definition Value in errno Error EAGAIN 11 Try again EBADF 9 Incorrect file number EDESTADDRREQ 89 Destination address required EFAULT 14 Incorrect address EFBIG 27 File too big EINTR 4 System call interrupted EINVAL 22 Invalid argument EIO 5 I/O error EPERM 1 Operation not allowed The easiest way to identify an error is to open a switch where the “errno” variable is the jump condition and each case is an error definition. Next, let us look at an example where we try to enter a descriptor with a negative sign, resulting in an error. To identify an error, we use the “if” condition that we saw in the previous snippet. To identify it, we open a switch with the three most common errors that this function can produce. #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> int main() { int fd,n; char buff[1024]; char path[] = "Documents/example.txt"; fd = open(path, O_RDONLY); n = read(99999999, buff, 1024); if (n == -1){ switch(errno){ case EBADF:{ printf("Bad file number. Error: %i\n", errno); break;} case EINVAL:{ printf("Invalid argument. Error: %i\n", errno); break;} case EIO:{ printf("I/O error . Error: %i\n", errno); break;} } } } As we can see in the following figure, the read() function returns an error when an invalid descriptor is passed as an input argument, and the value that is retrieved from the “errno” variable that is used as a jump condition allows us to identify the error when entering the EBADF case. Conclusion In this Linuxhint article, we showed you how to use the read() function, one of the most common functions that is implemented in the C language to read the files. We looked at its syntax and a section that describes its theoretical operation, input and output arguments, and its data types. Afterwards, we implemented what we learned in a practical example with the code and images that show how to open and read a file using the open() and read() functions. To have the necessary means to troubleshoot a possible error when using this function, we added a special section that explains the methods that the C language provides to detect and identify the errors. View the full article
-
- programming
- system calls
-
(and 2 more)
Tagged with:
-
Rivals C# and Java are poised to switch places as the fourth and fifth most popular programming languages. View the full article
-
- programming
- development
-
(and 2 more)
Tagged with:
-
A string in C language is an array of characters that is terminated with a null character (\0). The string length is the number of characters in a string. In the string length ‘\0,’ a character is not counted. In the example shown above, the length of the string str is 6. In this tutorial, first, we will show how to use a user defined function to calculate length of a string, and then we will show you a built-in library function strlen(). We also show you the uses of the sizeof operator for string literals. String Length Using User Defined Function You can write a user defined function which returns the number of characters in a string. //Example1.c #include<stdio.h> int stringLength(char *str) { int i=0; while(str[i] != '\0') i++; return i; } int main() { char str[30]= "STRING"; printf("Length of the string str is => %d\n",stringLength(str)); return 0; } Here, we iterate the while loop from i = 0 until we do not encounter the ‘\0’ character. The value of i is increased by 1 in each iteration of the while loop. When the loop ends, the value of i is the length of the string. String Length Using Built-In Library Function The built-in library function strlen() can also be used to determine string length. strlen() function: Header file: string.h Syntax: size_t strlen (const char *str) Argument: This function takes an argument of the type pointer to char. Return value: This function returns the length of the string str. Note that size_t is just an alias of an unsigned integer. //Example2.c #include<stdio.h> #include<string.h> int main() { char str1[30]="STRING ARRAY"; char *str2; char *str3; str2 = str1; str3 = "STRING POINTER"; printf("Length of the string str1 is => %ld\n",strlen(str1)); printf("Length of the string str2 is => %ld\n",strlen(str2)); printf("Length of the string str3 is => %ld\n",strlen(str3)); printf("Length of the string "STRING LITERALS" is => %ld\n",strlen("STRING LITERALS")); return 0; } Here, we pass string array, string pointer, and string literal to the strlen function, and the function returns the length of the string. String Length Using sizeof Operator We also can use the sizeof operator for string length (only for string literal). But, we have to subtract 1 from the value returned by this operator, because it also counts the’\0’ character. For array and pointer, the sizeof operator returns the allocated size of the array and the pointer, respectively. //Example3.c #include<stdio.h> int main() { char str1[30] = "STRING"; char *str2 =str1; printf("Length of "STRING" is => %d\n",(sizeof("STRING") - 1)); printf("Allocated size of the str1 array is => %d\n",sizeof(str1)); printf("Size of the str2 pointer is => %d\n",sizeof(str2)); return 0; } Here, in Line no 9, we pass the string literal “STRING” and get the size, including the ‘\0’ character. So, we subtract 1 and get the actual size of the string. When we pass an array to the sizeof operator, it returns the allocated size of the array, which is 30, and when passing a character pointer, it returns the size of the pointer. Conclusion So, in this tutorial, we have shown you how string length can be calculated in various ways. You can use in your code whichever method is best suited for you. View the full article
-
- programming
- languages
-
(and 1 more)
Tagged with:
-
Forum Statistics
67.4k
Total Topics65.3k
Total Posts