I am trying to print a certain line of a file in c. So far I think I am successfully reading line 8 of my text file but my question is how do I print that line using this code?
Thanks!!
this is the code so far:
int lineNumber = 8;
static const char filename[] = "Text.txt";
FILE *file = fopen(filename, "r");
int count = 0;
if ( file != NULL )
{
char line[256]; /* or other suitable maximum line size */
while (fgets(line, sizeof line, file) != NULL) /* read a line */
{
if (count == lineNumber)
{
//use line or in a function return it
//in case of a return first close the file with "fclose(file);"
}
else
{
count++;
}
}
fclose(file);
}
This works perfectly fine.
Are you missing the main function OR is it just the code snippet you have posted ?
int lineNumber = 8;
static const char filename[] = "Text.txt";
int main()
{
FILE *file = fopen(filename, "r");
int count = 0;
if ( file != NULL )
{
char line[256]; /* or other suitable maximum line size */
while (fgets(line, sizeof line, file) != NULL) /* read a line */
{
if (count == lineNumber)
{
//use line or in a function return it
// //in case of a return first close the file with "fclose(file);"
printf("\n str %s ", line);
fclose(file);
return 0;
}
else
{
count++;
}
}
fclose(file);
}
return 0;
}
Related
I am trying to write a program in C within a file pointer, but the problem is I only managed to write the file path like this:
char *line = gtline("/home/ubuntu/games/cards-against-humanity/black-cards/single/1/file1.txt", 3);
but I would like to replace /home/ubuntu/games with something else so I can download the whole directory /cards-against-humanity and the program still points to the file /file1.txt.
I've tried with /~ and with /. but it gives me Segmentation fault I suppose when the program trys to open the file.
Thanks in advance.
Update: gtfile function is a function i created by myself here's the declaration:
char *gtline(char *s, int i)
{
FILE *file;
char *filename = s;
static char buffer[MAX_LINE];
int read_line = i;
file = fopen(filename, "r");
if (file == NULL)
{
printf("Error opening file.\n");
fclose(file);
return NULL;
}
bool keep_reading = true;
int current_line = 1;
do
{
fgets(buffer, MAX_LINE, file);
if (current_line == read_line)
{
keep_reading = false;
}
if (feof(file))
{
keep_reading = false;
}
else
{
buffer[strlen(buffer)-1] = '\0';
}
current_line++;
} while (keep_reading);
fclose(file);
return buffer;
}
i am trying to read from a text file and store it into an array character by character, ive tested it out by trying to print or check the ii count but it doesn't seem to be storing, any help would be muchly appreciated
char *readFile(char* filename)
{
FILE* f;
int ii = 0;
char* file = (char*)malloc(1000*sizeof(char));
char ch = '\0';
f = fopen(filename,"r");
if(f == NULL)
{
printf("Error opening file '%s'.\n", filename);
}
else
{
while ((ch = fgetc(f)) != EOF)
{
printf("%c",ch);
file[ii] = (char) ch;
ii++;
}
}
/* file[ii] = '\0'; setting last character as null*/
printf("\n");
fclose(f);
free(file);
return file;
}
I have commented out the line containing the code to free the character array before returning, which was basically making the pointer invalid. I have also changed the type of the variable "ch" to int as fgetc() returns integer.
#include <stdio.h>
#include <stdlib.h>
char *readFile(char* filename)
{
FILE* f;
int ii = 0;
char* file = (char*)malloc(1000*sizeof(char));
int ch; //changed to int from char.
f = fopen(filename,"r");
if(f == NULL)
{
printf("Error opening file '%s'.\n", filename);
}
else
{
while ((ch = fgetc(f)) != EOF)
{
// printf("%c",ch);
file[ii] = (char) ch;
ii++;
}
}
/* file[ii] = '\0'; setting last character as null*/
printf("\n");
fclose(f);
//free(file); //commented this line out
return file;
}
int main()
{
char *filename = "sample.txt";
char *file_arr = readFile(filename);
printf("%s \n",file_arr);
return 0;
}
I am trying to read strings from a file. File contains below text:
<1a>This is line 1<1a>
<2f>This is line 2<2f>
<3c>This is line 3<3c>
In my program I get this value 1a or 2f. Based on this, I need to extract that particular line like for 2f, I only need to read This is line 2 and save it in a buffer.
I have been able to read write using fopen fput but dont know how to read this.Can anyone please point me into some right direction which shows how to read this. Any demo code. Thanks.
This should do the trick:
#include <stdio.h>
#include <string.h>
int extract_line (char* line, char* buffer, char* ctag)
{
char line_buffer[255] = {0};
char* tagStart;
char* tagEnd;
if( strlen(line) < (sizeof(line_buffer)/sizeof(char)) )
{
strcpy(line_buffer,line);
}
else
{
printf("Line size is too big.\n");
return 1;
}
tagStart = strstr(line_buffer,ctag);
if(tagStart != NULL)
{
tagEnd = strstr(tagStart+1,ctag);
if(tagEnd != NULL && (tagEnd > (tagStart + strlen(ctag))))
{
*(tagEnd) = '\0';
strcpy(buffer, tagStart + strlen(ctag));
printf("%s\n",buffer);
}
else
{
printf("Could not find closing tag.\n");
return 1;
}
}
return 0;
}
int main ()
{
char buffer[255] = {0};
char line_buffer[255] = {0};
char tag[] = "<2a>";
char* cptr;
FILE* data;
data = fopen ("file.txt", "r");
if (data == NULL)
{
printf("\n Failed to open file!");
}
else {
while(( fgets( line_buffer, 255, data )) != NULL)
{
cptr = strstr(line_buffer,tag);
if(cptr == NULL)
{
continue;
}
if(!extract_line(line_buffer,buffer,tag))
{
//Do the rest of processing
puts(buffer);
strcpy(buffer,"");
}
}
fclose (data);
}
return 0;
}
Basicly, what you need to do is get the tag field and use it as a delimeter to exctract the token. Just get the line tag and then use it to exctract the data.
char* returnSpecificString(char* valueBetweenQuotes)
{
FILE* file= fopen("test.txt", "r"); // Open in reading only mode
char *line= malloc(sizeof(char[150]));
if (NULL == line) // Checks if enough memory
fprintf(stderr, "Not enough memory. \n");
else
{
while(fgets(line, sizeof(line), file)) //Iterate until end of file
{
if (strstr(line, valueBetweenQuotes) != NULL) // Meaning it's the line we want
return functionToExtractTextBetweenQuote();
}
}
return line;
}
As for the functionToExtractTextBetweenQuote() I advise you look functions like strtok() strchr()or sprintf() which will help you extract what you want from a string. I know this is unsufficiant but I ain't got the time to finish it now so I hope it will help you.
I have a text file with one number in each line.
I want to read a specific number of lines from this file , lets say the first 20, what is the way to do it?
I have the following piece of code.
FILE *ft;
ft=fopen(filename,"r");
for(int k=1; k<Nt+1; k=k+1)
{
fscanf(ft,"%lf\n",&curve3[k]);
printf("%lf\n",curve2[k]);
}
EDIT: I changed my code to
FILE *ft;
ft=fopen(filename,"r");
int k=1;
while(!feof(ft))
{
if(k<=Nt)
{
fscanf(ft,"%lf\n",&curve2[k]);
//printf("%lf\n",curve2[k]);
}
k=k+1;
}
It still doesn't seem to work.
With this code you can read a file line by line and hence read a specific line from the text file. So, you can modify the code.
lineNumber = x;
static const char filename[] = "file.txt";
FILE *file = fopen(filename, "r");
int count = 0;
if ( file != NULL )
{
char line[256]; /* or other suitable maximum line size */
while (fgets(line, sizeof line, file) != NULL) /* read a line */
{
if (count == lineNumber)
{
//use line or in a function return it
//in case of a return first close the file with "fclose(file);"
}
else
{
count++;
}
}
fclose(file);
}
else
{
//file doesn't exist
}
Here is the code:
int main()
{
struct vinnaren
{
char vinnare[20];
int artal;
};
struct vinnaren v[10];
int inputrader;
int antalrader; //I want antalrader to be equal to the first
//line in test.txt(the first line is "5")
char file_name[256] = "test.txt";
char buf[512];
FILE *f = fopen(file_name, "r");
if (!f)
{
exit(0);
}
while (fgets(buf, sizeof buf, f))
{
printf("%s", buf);
}
fclose(f);
}
This is the code I have. I want to make it so that
antalrader = line1 in the file test.txt
How do I read a specific line from the file?
With this code you can read a file line by line and hence read a specific line from the text file:
lineNumber = x;
static const char filename[] = "file.txt";
FILE *file = fopen(filename, "r");
int count = 0;
if ( file != NULL )
{
char line[256]; /* or other suitable maximum line size */
while (fgets(line, sizeof line, file) != NULL) /* read a line */
{
if (count == lineNumber)
{
//use line or in a function return it
//in case of a return first close the file with "fclose(file);"
}
else
{
count++;
}
}
fclose(file);
}
else
{
//file doesn't exist
}
I got a really simple answer but I don't know if it is helping anyone:
int OpenCommand(int idOfCommand)
{
fscanf(file_ptr, "%[^idOfCommand]",a[idOfCommand]);
printf("%d\n", a[idOfCommand]);
system("pause");
return 0;
}