This question already has answers here:
How can I read an input string of unknown length?
(11 answers)
Closed 3 years ago.
I have been trying to learn C, and was wondering: how would one get a string with an unknown length in C? I have found some results, but am not sure how to apply them.
If you're ok with extensions to the Standard, try POSIX getline().
Example from documentation:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
char *line = NULL;
size_t len = 0;
ssize_t read;
fp = fopen("/etc/motd", "r");
if (fp == NULL)
exit(1);
while ((read = getline(&line, &len, fp)) != -1) {
printf("Retrieved line of length %zu :\n", read);
printf("%s", line);
}
if (ferror(fp)) {
/* handle error */
}
free(line);
fclose(fp);
return 0;
}
Related
If I have a file which contains a '\n' on virtually every line, and I use getline() in a while loop to read the content, is this bad practice?
My understanding is that getline() will be called numerous times for each '\n' char reached, and so realloc() will be called each time also. Which seems inefficient?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv) {
FILE *fp = fopen("file.txt", "r");
if (fp == NULL) {
perror("Unable to open file: ");
exit(1);
}
char *buffer = NULL;
size_t len = 0;
ssize_t characters;
while ((characters = getline(&buffer, &len, fp)) != -1) {
fputs(buffer, stdout);
}
fclose(fp);
free(buffer);
buffer = NULL;
return 0;
}
There is no problem calling getline in a loop as you do. As a matter of fact, this exactly the intended use case and used in the example in the man page.
realloc is only called if the array allocated so far is too short for the current line, thus it will be called very little and you can even lower the number of calls by allocating an initial array and set its length in the len variable.
Since getline returns the number of characters read, you could write the line using fwrite instead of fputs. Note however that the behavior is subtly different: fwrite will output lines read from the file containing embedded null bytes, whereas fputs would stop on the first null byte. This is usually not an issue as text files usually do not contain null bytes.
Here is a modified version:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv) {
FILE *fp = fopen("file.txt", "r");
if (fp == NULL) {
fprintf(stderr, "Unable to open file %s: %s\n",
"file.txt", strerror(errno));
return 1;
}
char *buffer = NULL;
size_t len = 0;
ssize_t characters;
#if 1
// optional code to show how to start with a preallocated buffer
if ((buffer = malloc(256)) != NULL)
len = 256;
#endif
while ((characters = getline(&buffer, &len, fp)) != -1) {
fwrite(buffer, 1, characters, stdout);
}
fclose(fp);
free(buffer);
return 0;
}
I have to read in a stream of numbers from a text file into my code using stdin by passing my program the file like ./msort <segment count> <file.txt.
I tried 2 methods of reading in the numbers, however these methods only work when I read them line by line as strings. I tried following a few links to type and typecast the string to an int, however I had no luck. The integer outputs are all just garbled. This is the code:
#define BUFFERSIZE 10
int main(int argc, char **argv) {
if (argc != 2) {
printf("Usage: %s <segment count>\n", argv[0]);
return 1;
}
char *line = NULL;
size_t size;
while (getline(&line, &size, stdin) != -1) {
line[strcspn(line, "\n")] = 0;
printf("%d\n", (int)*line);
}
// char *text = calloc(1, 1), buffer[BUFFERSIZE];
// while (fgets(buffer, BUFFERSIZE, stdin))
// {
// text = realloc(text, strlen(text) + 1 + strlen(buffer));
// strcat(text, buffer);
// buffer[strcspn(buffer, "\n")] = 0;
// printf("%d\n", (int)*buffer);
// }
return 0;
}
Could you please help me out with this?
screenshot of code and text file
Use strtol to read numbers from strings:
#include <errno.h> // errno
#include <stdlib.h> // strtol
// ...
char *line = NULL;
size_t size = 0;
errno = 0; // Reset errno before calling strtol.
char *endptr; // Used to check where strtol ended reading a number.
while (getline(&line, &size, stdin) != -1) {
long val = strtol(line, &endptr, 10); // Read a number from the line.
// Double-check that a number was indeed read. If you don't want to errorcheck,
// you can remove this, take out "#include <errno.h>", "errno = 0" and replace
// &endptr with NULL.
if (errno != 0) {
fprintf(stderr, "strtol: %s\n", strerror(errno));
return 1;
} else if (endptr == line) {
fprintf(stderr, "strtol: no digits were found\n");
return 1;
}
printf("%d\n", val);
}
I think there are some problems with your code.
You want to read lines from file specified as command-line argument(argv[1]) but you're passing stdin as parameter. you should open the file using fopen and use that file pointer in getline method like shown below.
You can then use sscanf to read integer values from the line string.
FILE *pFile = fopen(argv[1], "r");
if (!pFile) {
printf("Error opening file %s\n", argv[1]);
return EXIT_FAILURE;
}
int currentNum;
while (getline(&line, &size, pFile) != -1) {
line[strcspn(line, "\n")] = 0;
sscanf(line, "%d", ¤tNum);
printf("%d\n", currentNum);
}
I'm writing a 'C' code that stores the TCP payload of captured packets in a file (payload of each packet is separated by multiple "\n" characters). Using C, is it possible to search for a particular string in the file after all the packets are captured?
P.S : The file can be very large, depending upon the number of captured packets.
Read the file line by line and search using strstr.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
FILE * fp;
char * line = NULL;
size_t len = 0;
ssize_t read;
char * pos;
int found = -1;
fp = fopen("filename", "r");
if (fp == NULL)
exit(EXIT_FAILURE);
while ((read = getline(&line, &len, fp)) != -1)
{
pos = strstr(line,"search_string");
if(pos != NULL)
{
found = 1;
break;
}
}
if(found==1)
printf("Found");
else
printf("Not Found");
fclose(fp);
if (line)
free(line);
exit(EXIT_SUCCESS);
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
How do get number line of file text on c ?. Help me .
Get sum number line.
I want read a file text.
EX:
for( line = 0; line < sumline; line ++) {
printf("char in line");
}
In case i understood the question :
#include <stdio.h>
#include <string.h>
main()
{
FILE *fp;
char * line;
size_t len = 0;
ssize_t read;
int lines = 0;
fp = fopen("input.txt", "r");
if( fp != NULL ){
while ((read = getline(&line, &len, fp)) != -1){
lines ++;
printf("%s\n", line);
}
fclose(fp);
}
printf("number of lines : %d\n", lines);
}
to count how many lines in your file
Try this:
`int lines = 0;
while ((read = getline(&line, &len, fp)) != -1) {
lines++;
}
cout << lines << endl;`
You can use the following function to get the number of lines inside a file.
#include <stdio.h>
// get the number of lines inside file
int getLineCnt(char *pcFileName) {
FILE *fp;
int lines=0;
fp = fopen(pcFileName, "r");
if(fp == NULL) { return -1; }
while (EOF != (fscanf(fp, "%*[^\n]"), fscanf(fp, "%*c"))) {
++lines;
}
io_fclose(fp);
return lines; ///\ retval number of lines
}
This question already has answers here:
Split string with delimiters in C
(25 answers)
Closed 9 years ago.
I have a program that read File in C. Now I want to put the strings divide by space into an array. How do I do it?
#include <stdio.h>
int main()
{
char line[30];
char names[100][20];
int sizes[100];
int i = 0;
FILE *fp;
fp = fopen("in.txt", "rt");
if(fp == NULL)
{
printf("cannot open file\n");
return 0;
}
while(fgets(line, sizeof(line), fp) != NULL)
{
printf(line);
i++;
}
fclose(fp);
return 0;
}
Have a look at the function strtok or strtok_r
http://www.cplusplus.com/reference/cstring/strtok/?kw=strtok