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 6 years ago.
Improve this question
I would like to display the names of files without their .txt extension. I already have the file + extension stored from dir->d_name.
It made sense in my head to do it the following way:
char filename[size]; //assume this already contains name followed by.txt
filename[size-4] = '\0';
I've attempted this, but I am still getting the name with its extension. Perhaps I don't fully understand how the null terminator works.
Any suggestions?
This:
filename[size-4] = '\0';
will not work, since size is not (necessarily) the length of the string.
Try:
filename[strlen(filename) - 4] = '\0';
Minimal example:
#include <stdio.h>
#include <string.h>
#define SIZE 20
int main(void) {
char filename[SIZE] = "test.txt";
printf("%s\n", filename);
// -4 for .txt
filename[strlen(filename) - 4] = '\0';
printf("%s\n", filename);
return 0;
}
Output:
gsamaras#gsamaras:~$ ./a.out
test.txt
test
PS - You may want to check if .txt really exists.
Or*, by using strstr(), you could do this and check if .txt actually exists:
#include <stdio.h>
#include <string.h>
int main (void) {
char str[] = "test.txt";
char *pch;
pch = strstr(str, ".txt");
if(pch) // if's body won't execute if .txt is absent
*pch = '\0';
puts(str);
return 0;
}
*as #user3386109 said
Trying doing
strncopy(noExt_string, filename, strlen(filename) - 4)
This should copy the contents of filename in to noExt_string without the last 4 characters.
If you only want to print the filename without the .txt extension then you can do it without change the string.
write(1, filename, strlen(filename) - 4);
Related
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 2 years ago.
Improve this question
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
FILE *filePointer ;
char dataToBeRead[50];
filePointer = fopen("input.txt", "r") ;
while( fgets ( dataToBeRead, 50, filePointer ) != NULL )
{
printf( "%s" , dataToBeRead ) ;
}
fclose(filePointer) ;
}
And this is the text file enter image description here. I want to take the word in the middle of each line and print it.
You can use
strtok(str, ",")
strtok(NULL, ",")
printf("%s\n", str);
This is not thread-safe or re-entrant but you're unlikely to care about that for this exercise.
If this is too fancy (I assume this is a student exercise and a simpler version may be desired) try stepping through the string character-by-character, counting commas and using putchar during the appropriate section.
As with many tasks in C, there are lots of ways to do this one. One suggestion could be to use the strstr() and snprintf() functions to help find the beginning of the search word then truncate the rest of line to include only the word of interest: (your code modified to use this approach)
while( fgets ( dataToBeRead, 50, filePointer ) != NULL )
{
char *temp = strstr(dataToBeRead, "SearchTerm");
if(temp != NULL)
{
char found[50]={0};
snprintf(found, strlen("searchTerm"), temp)
printf( "%s" , found) ;
}
...
Another way, (simpler, but perhaps not as satisfying) simply test the input buffer for existence of the search term using strstr() (as the above example does), but if strstr() does not return NULL, then simply print out the given search term without bothering to parse its twin from out of the line buffer.
Aside: Magic numbers (Such as 50 in your example: char dataToBeRead[50]; are not as useful as human readable and understandable variables and/or #define values, eg:
#define MAX_FILE_LINE_LEN 50
Then in your code, everywhere 50 would be used, replace it with MAX_FILE_LINE_LEN
And, while on the topic, use a more reasonable length than 50. At least 80, but 260 would not be too big for most systems either.
This question already has answers here:
getline line by line and then store entire lines in an array in C [closed]
(3 answers)
Closed 5 years ago.
First, I'm sorry if another topic is relative to my issue, but I can't reach one which is appropriate.
I will try to be clear as much as possible.
I'm realizing a course project, which need to take about 10 entires text files to save them in an array, then treat the datas. (treating isn't an issue)
I use fgets to get all lines, they I pass the s "string" to an char$ []
Code :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int* argc, char* argv[]){
char* c = "./example.txt";
char s[500];
char* lignes[100];
int sizeLignes = 0;
printf("%s \n\n", c);
FILE* myFile = NULL;
myFile = fopen(c, "r");
if (myFile != NULL){
int n;
while ( fgets(s, 500, myFile) != NULL ){
printf("%d \n\n", sizeLignes);
lignes[sizeLignes] = s;
printf("%s", lignes[sizeLignes]);
sizeLignes++;
}
printf("%s", lignes[1]);
printf("%s", lignes[2]);
printf("%s", lignes[3]);
}else{
printf("Wrong file");
}
fclose(myFile);
return 0;
}
My s var is good, if I print it every loop, it's good.
And if I print lignes[sizeLignes] inside the loop, it's good too.
Put if I try to print the value outside... It's like keeping the 4 last words or something like that.
Any idea?
Do you need more informations?
Thanks in advance,
Izio
You should use strcpy(lignes[sizeLignes], s) instead of lignes[sizeLignes] = s.
You may indeed use strcpy_s too. You also should allocate memory for the string.
So I recommend the next code
lignes[sizeLignes] = malloc(500);
strcpy(lignes[sizeLignes], s);
Free the dynamic memory when it will be not required.
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 6 years ago.
Improve this question
I'm very new to this. I am trying to re-write this code in order to remove the buffer overflow that is picked up in lines 12 + 19.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUF_SIZE (1024)
int main(int argc, char* argv[]) {
char* inBuf;
char* outBuf;
char* fmt = "the winner is: %s";
inBuf = (char*) malloc(BUF_SIZE);
if (inBuf == NULL) {
return -1;
}
read(0, inBuf, BUF_SIZE);
outBuf = (char*) malloc(BUF_SIZE);
if (outBuf == NULL) {
return -1;
}
sprintf(outBuf, fmt, inBuf);
fprintf(stdout, "%s\n", outBuf);
fprintf(stderr, "%s\n", outBuf);
free(inBuf);
free(outBuf);
}
If someone could provide some insight on the best way to approach this? would be much appreciated thank you.
Because you use the read function to read user input, you're reading raw bytes as opposed to a string. So what it read in doesn't include a null terminating byte, so you don't have a null terminated string since the buffer returned by malloc is uninitialized.
Use calloc instead of malloc, which returns a buffer initialized to all zeros.
inBuf = calloc(BUF_SIZE + 1, 1);
Note that this leaves an extra byte for a terminating null character.
You should also be checking the return value of read for an error, and you shoudn't cast the return value of malloc/calloc/realloc.
Your output buffer size is also too small. It should be at least the size of the input string plus the format string.
outBuf = (char*) malloc(BUF_SIZE + 1 + strlen(fmt));
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
I'm making a RPG game in C, and I need to read from a single file. Having multiple files is very tedious. Like "health.dat", "energy.dat", "money.dat" etc. I want to put them into one "data.dat", is this possible?
I just want to read specific line from a file
If line 1 has "number 1", then it should go to the "a" variable, line 2 should go to the "b" variable, etc.
Many thanks.
It is possible.
you can use the array of pointers in the fgets function.
char *fgets(char *s, int size + 1, FILE *stream);
fgets (array,size + 1,stream);
where array is *array[size];
You can achieve what you describe using the fgets function as follows:
#include <stdio.h>
#include <stdlib.h>
const int MAX_LENGTH = 256;
int main (void)
{
// Open the file
FILE* file = fopen ("data.dat", "r");
// Read the lines
char a[MAX_LENGTH];
fgets (a, MAX_LENGTH - 1, file);
char b[MAX_LENGTH];
fgets (b, MAX_LENGTH - 1, file);
// ...
// Close the file
fclose (file);
return EXIT_SUCCESS;
}
Set the MAX_LENGTH variable to the maximum expected length of a line in your file. You should also test fopen and fgets for returning NULL, as both are error conditions.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I 12 0
I 9 1
I 26 0
I 25 2
B 26
P 0
R 25
A
So, what I need to do is read a file containing these characters/numbers and whenever I encounter a letter, I call a function to process whatever comes after the letter (aka the numbers).
For example:
When reading "I" I have to call the function to INSERT a certain number in a certain level of a Skip List; or when reading B, I need to search for a specific number in the Skip List, etc.
Problem is I'm really bad at reading from a file, can you guys enlighten me?
You can do this with file operations in c,
i am just giving you hints,
FILE *pFilePtr; // file pointer(handle of file)
pFilePtr = fopen(argv[1],"r");
//define buffer to store data read line by line data
char buf[32]={0};
//Now you can run a while loop to read entire file
with fread() to get whole first line(until '\n')
while(!feof(pFilePtr))
{
if(NULL != fgets(buf,32,pFilePtr))
// perform string operation on buffer to extract letters and digits
// and according to that call functions you need
}
#include <stdio.h>
#include <string.h>
int main(void) {
FILE *fptr;
char mystring[20];
int number;
fptr = fopen("Input.txt", "r");
while(fscanf(fptr , "%s %d", mystring, &number) != EOF) {
printf("%s %d\n", mystring, number);
if(strcmp(mystring, "I") == 0) {
printf("Implement the reqd function here\n");
}
}
}