Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am working on a project. there is a .txt file that includes negative integers like this
0 -1 0
-1 20 -1
0 -1 0
My problem is I couldn't read negative numbers. What is your suggestions for this problem?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char * argv[]) {
FILE *fptr;
char letter;
fptr = fopen(argv[1],"r");
if(fptr == NULL){
printf("Please provide an argument\n");
exit(1);
}
while ( ( letter = fgetc(fptr) ) != EOF ) {
printf("%c",letter);
}
printf("\n");
fclose(fptr);
return 0;
}
You can try this to read the lines from the file and then parse your numbers.
getline reads a line from your file and strtok then gives you a string until the specified delimeter (space in your case). Hope this helps.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char * argv[]) {
FILE * fptr = fopen(argv[1],"r");;
char * line = NULL;
size_t lineSize = 0;
if(fptr == NULL){
printf("Please provide an argument\n");
exit(1);
}
while(getline(&line, &lineSize, fptr) != -1) {
line[strcspn(line, "\n")] = 0;
printf("%s\n", line);
char * token = strtok(line, " ");
printf("%s\n", token);
while((token = strtok(NULL, " ")) != NULL) {
printf("%s\n", token);
}
}
fclose(fptr);
return 0;
}
Related
This question already has answers here:
How should character arrays be used as strings?
(4 answers)
Closed 12 months ago.
I have a file with an unknown number of strings and each of these strings is of an unknown length.
I would like to make each line of the file its own string in an array of strings.
I tried to use dynamic allocation in a char** array, but I don't think I'm approaching this correctly.
Below is the code I have tried. It's getting stuck in an infinite loop, and I can't figure out why.
(The text file I'm reading from ends with a line break, by the way.)
#include <getopt.h> //for getopts
#include <sys/stat.h> //to do file stat
#include <dirent.h>
#include <string.h>
#include <pwd.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h> //user macros
#include <stdlib.h>
#include <stdbool.h>
#include <libgen.h>
#include <errno.h>
int main(int argc, char *argv[]) {
//storing the filename inside string
char* filename = argv[1];
FILE *fp1 = fopen(filename, "r");
if (fp1 == NULL) {
fprintf(stderr, "Error: Cannot open '%s'. No such file or directory.\n", filename);
return EXIT_FAILURE;
}
/**
* we begin by getting the number of numbers in the file
* the number of numbers = number of lines = number of line breaks
*/
size_t numNumbers = 0;
// while((fscanf(fp1, "%*[^\n]"), fscanf(fp1, "%*c")) != EOF){
// numNumbers = numNumbers + 1;
// }
char c;
while((c = fgetc(fp1)) != EOF){
if(c == '\n'){
numNumbers++;
}
}
fclose(fp1);
FILE *fp2 = fopen(filename, "r");
char** arrayOfStrings = malloc(numNumbers * sizeof(char*));
for(int i = 0; i < numNumbers; i++) {
int len = 0;
if(((c = fgetc(fp1)) != '\n') && (c != EOF)){
len++;
}
arrayOfStrings[i] = malloc(len * sizeof(char));
}
printf("hello1\n");
//for(int i = 0; i < numNumbers; i++){
// fscanf(fp2, "%s", (arrayOfStrings[i]));
//}
fclose(fp2);
// for(int i = 0; i < numNumbers; i++){
// fprintf(stdout, "%s", arrayOfStrings[i]);
// }
return 0;
}
(I'm very new to C, so please go easy on me!)
In C, strings are terminated with a '0' byte, so it looks like your malloc for each string is 1 character too short -- you've only allowed space for the text.
In addition, you mean the count for the size of each line to be a while loop, not an if statement - right now you are counting each line as length "1".
Finally, you are reading off the end of the file in your commented out fscanf code because you haven't closed and reopened it.
Assuming you want to split the input to the strings by the newline character, would you please try:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
char *filename; // filename to read
char **arrayOfStrings = NULL; // array of strings
char line[BUFSIZ]; // line buffer while reading
char *p; // temporal pointer to the input line
int i, num; // counter for lines
FILE *fp; // file pointer to read
if (argc != 2) {
fprintf(stderr, "usage: %s file.txt\n", argv[0]);
return EXIT_FAILURE;
}
filename = argv[1];
if (NULL == (fp = fopen(filename, "r"))) {
perror(filename);
return EXIT_FAILURE;
}
// read the input file line by line
while (fgets(line, BUFSIZ, fp)) {
if ((p = strrchr(line, '\n'))) *p = '\0'; // remove trailing newline, if any
if ((p = strrchr(line, '\r'))) *p = '\0'; // remove trailing cr character, if any
if (NULL == (arrayOfStrings = realloc(arrayOfStrings, (num + 1) * sizeof(char **)))) {
// enlarge the array according to the line count
perror("realloc");
return EXIT_FAILURE;
}
if (NULL == (arrayOfStrings[num] = malloc(strlen(line) + 1))) {
// memory for the string of the line
perror("malloc");
return EXIT_FAILURE;
}
strcpy(arrayOfStrings[num], line);
num++;
}
// print the strings in the array
for (i = 0; i < num; i++) {
printf("%d %s\n", i, arrayOfStrings[i]);
}
fclose(fp);
return 0;
}
If the input file looks something like:
This
is
the
input.
Then the output will be:
0 This
1 is
2 the
3 input.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am confused that how to give break line after every word which is present in a file.
Words in text file
Name Date of birth <---- I put this in code
John 02\02\1999 <---- I want to jump to this line
I want this
Here is your: Name
Here is your: Date of Birth
But it is giving me this
Here is your: N
Here is your: a
Here is your: m
Here is your: e
And I don't know how to get it.
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE * fr = fopen("/home/bilal/Documents/file.txt","r");
char ch;
if(fr != NULL){
while(!feof(fr)){
ch = fgetc(fr);
printf("Here is your %c\n: ", ch);
}
fclose(fr);
}
else{
printf("Unable to read file.");
}
return 0;
}
Within your while loop instead of immediately printing the character that you read, store the char in a char array. Add an if statement that does a comparison that checks if the read char is a space character. If it is you should print the stored array and set the index of the array back to 0.
Example:
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE * fr = fopen("file.txt","r");
char ch[100];
int index = 0;
if(fr != NULL){
while((ch[index] = fgetc(fr)) != EOF){
//printf("%c\n", ch[index]);
if(ch[index] == ' ') {
ch[index] = '\0';
printf("Here is your: %s\n", ch);
index = 0;
}
else {
index++;
}
}
fclose(fr);
}
else{
printf("Unable to read file.");
}
return 0;
}
Based on the line of text of the file provided we can assume that if the first letter of the word is in uppercase then it is the start of the next sentence:
Name Date of birth ID card number Phone number Address Account Fixing year
And use this to divide the line into sentences.
So here is the code by Christopher changed to group the words into sentences:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(){
FILE * fr = fopen("file.txt","r");
char ch[100];
int index = 0;
if(fr != NULL){
while((ch[index] = fgetc(fr)) != EOF){
if(index > 0 && ch[index-1] == ' ' && isupper(ch[index])) {
ch[index-1] = '\0';
printf("Here is your: %s\n", ch);
ch[0] = ch[index];
index = 1;
}
else {
index++;
}
}
ch[index] = '\0';
printf("Here is your: %s\n", ch);
fclose(fr);
}
else{
printf("Unable to read file.");
}
return 0;
}
I have a file like this
GET /index.html k
GET /docencia.html k
GET /ejemplo.html k
and I want to read it line by line and split it up with this delimiter " " but is giving me this error: segmentation fault(core dumped) and I don't know what to try.
This is my code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
char ordenes[150];
char *orden[3];
char *token;
int tok;
FILE *fp;
fp = fopen(argv[1], "r");
if (fp == NULL) {
printf("File error");
exit(1);
}
while (feof(fp) == 0) {
fgets(ordenes, sizeof(ordenes), fp);
printf("%s \n", ordenes);
token = strtok(ordenes, " ");
tok = 0;
while (token != NULL) {
orden[tok] = strdup(token);
tok++;
token = strtok(NULL, " ");
}
printf("\n%s\n", orden[0]);
printf("\n%s\n", orden[1]);
printf("\n%s\n", orden[2]);
}
fclose(fp);
}
The error shows when I call the first strdup. If I try to print the token just after I call the first strtok, it fails too (the same segmentation fault core dumped) so I guess the problem is with the strtok.
You do not include <string.h>, so the compiler applies the default argument promotions on the signature of strtok, in particular it considers that strtok returns an int.
So the compiler will apply an operator of coercion from int to pointer to char at the assignment
token = strtok(ordenes, " ");
and this assignment will be compiled as
token = (int->char*) strtok(ordenes, " ");
There are multiple problems in your code:
As alinsoar diagnosed with a sharp eye, you do not include <string.h>. strtok is not defined, the compiler must assume it returns an int, which it does not, and this int is silently converted to a char *. The code generated invokes undefined behavior and will most likely crash on 64-bit targets. You should compile with all warnings enabled to let the compiler help avoid this kind of silly mistake. gcc -Wall -W or clang -Weverything...
You do not check if command line arguments have been passed to your program before calling fp = fopen(argv[1], "r");. If no arguments are passed, argv[1] is a null pointer.
while (feof(fp) == 0) is incorrect, read Why is “while ( !feof (file) )” always wrong? . You should instead write while (fgets(ordenes, sizeof(ordenes), fp)) {...
You do not check if tok < 3 before storing token into the orden array. If the line has more than 3 fields, you will cause a buffer overflow.
You do not check if 3 tokens were indeed found before printing all 3 entries in orden. This too might invoke undefined behavior, especially if fgets() failed to read a line, which you do not check.
Here is an improved version:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
char ordenes[150];
char *orden[3];
char *token;
int i, tok;
if (argc < 2) {
fprintf(stderr, "Missing command line argument\n");
exit(1);
}
FILE *fp = fopen(argv[1], "r");
if (fp == NULL) {
fprintf(stderr, "Cannot open input file %s: %s\n",
argv[1], strerror(errno));
exit(1);
}
while (fgets(ordenes, sizeof(ordenes), fp)) {
printf("%s", ordenes);
token = strtok(ordenes, " ");
for (tok = 0; tok < 3 && token != NULL; tok++) {
orden[tok] = strdup(token);
token = strtok(NULL, " ");
}
for (i = 0; i < tok; i++) {
printf("%s\n", orden[i]);
free(orden[i]);
}
printf("\n");
}
fclose(fp);
return 0;
}
For starters you should change the condition in the outer loop statement the following way
while ( fgets(ordenes, sizeof(ordenes), fp) != NULL )
The condition in the inner loop should be written at least like
while ( tok < 3 && token != NULL) {
The tokens should be outputted in a loop and the allocated memory must be freed. For example
for ( int i = 0; i < tok; i++ )
{
printf("\n%s\n", orden[i]);
free( orden[i]);
}
You can do the following:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void play_with_token(char *token, char const *delim)
{
if (token == NULL)
return;
printf(" %s", token);
play_with_token(strtok(NULL, delim), delim);
}
int main(int argc, char *argv[])
{
if (argc != 2)
return 1;
FILE *fp = fopen(argv[1], "r");
if (fp == NULL)
return 1;
char *line = NULL;
size_t len = 0;
ssize_t read;
while ((read = getline(&line, &len, fp)) != -1) {
printf("parsing line :");
char const *delim = " ";
play_with_token(strtok(line, delim), delim);
printf("\n");
}
free(line);
fclose(fp);
}
try this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]){
char ordenes[150];
char *orden[3];
char *token;
int tok;
FILE *fp;
fp = fopen (argv[1], "r");
if(fp==NULL){
printf("File error");
exit(1);
}
while(fgets(ordenes, sizeof(ordenes), fp)){
printf("%s\n",ordenes);
token = strtok(ordenes, " ");
tok = 0;
while (token != NULL){
orden[tok++] = strdup(token);
token = strtok(NULL," ");
}
printf("\n%s\n",orden[0]);
printf("\n%s\n",orden[1]);
printf("\n%s\n",orden[2]);
free(orden[0]);free(orden[1]);free(orden[2]);
}
fclose(fp);
}
This question already has answers here:
Why does 'fopen' return a NULL pointer?
(8 answers)
Closed 8 years ago.
Why does fopen() return a null pointer?
I'm trying to save the parameters after BRIDGE and after LAN (respectively 4 and 5) in cont_br and cont_lan, but fopen() doesn't work...
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
void read_file(char file[]) {
char cont, *str, *ctrl_str;
int x=0, cont_br, cont_lan;
FILE *file_stream;
if (file_stream = fopen(file, "r")) {
while( !feof(file_stream) ) { //Check the file dimension
fgetc( file_stream );
x++;
}
x--;
str = (char*) malloc(sizeof(char) * x+1);
fseek(file_stream, 0, SEEK_SET); // Return at the beginning of the file
fread(str, x, 1, file_stream);
char delims[] = "#";
char *result = NULL;
result = strtok( str, delims);
while (result != NULL) {
if (result == "BRIDGE") { //Check the different "blocks" in the txt file
result = strtok(NULL, delims);
cont_br = atoi(result);
printf("Number of bridges: %d\n", cont_br);
}
result = strtok(NULL, delims);
if (result == "LAN") {
result = strtok(NULL, delims);
cont_lan = atoi(result);
printf("Number of Lan: %d\n", cont_lan);
}
break; //
}
}
printf("Error: can't open the file! errno: %d\n", errno);
fclose(file_stream);
}
int main() {
char file[] = "Config.txt";
read_file(file);
return 0;
}
And this is the Config.txt file:
BRIDGE#4#
LAN#5#
192.168.0.1
192.168.1.1
192.168.2.1
192.168.3.1
192.168.4.1
#
LINK#
B1:3000,L1
B1:3001,L2
B1:3002,L3
B2:3000,L4
B2:3001,L5
B3:3000,L1
B4:3000,L3
B5:3000,L2
B2:3002,L3
Whenever fopen fails then print the error number (errno).
#include <error.h>
You should include the standard errno.h and print the value of error in your code. Then look at the error code and find the reason.
Example
#include <stdio.h>
#include <errno.h>
int main()
{
errno = 0;
FILE *fb = fopen("/home/jeegar/filename", "r");
if (fb==NULL) {
printf("Error %d \n", errno);
printf("It's null");
}
else
printf("working");
}
This way if fopen fails then it will set the error number. You can find those error number lists in fopen.
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
}